Get the App
SLTechnology News&Howtos  ›  Development  › 

What is Java generic erasure?

Shulou Source: shulou.com Published: 2022-06-01 21:58:11 09月20日 Update

This article mainly introduces Java generic erasure is what the relevant knowledge, detailed and easy to understand, simple and fast operation, has a certain reference value, I believe we read this Java generic erasure is what the article will gain, let's take a look at it.

Generics information exists only during code compilation, but generics-related information is erased during java runtime (after the bytecode file has been generated), a technical term called type erasure.

generic erasure concept

Generics information exists only during code compilation, but generics-related information is erased during java runtime (after the bytecode file has been generated), a technical term called type erasure. Let's look at an example:

ArrayList l1 = new ArrayList();ArrayList l2 = new ArrayList(); System.out.println(l1.getClass()==l2.getClass());

Run the code and the result is True

This is because ArrayList and ArrayList are both List.class in jvm, which is equivalent to List in jvm

Using Type to Erase "Bad Things"

As you all know, the following code l.add(123) cannot compile because 123 is not of type String, which is one of the benefits of using generics.

ArrayList l=new ArrayList();l.add("abc");l.add(123);

But we understand the principle of generic erasure, and we can skillfully use this principle in combination with reflection knowledge to do some "bad things," such as:

ArrayListl=new ArrayList(); l.add("abc"); try { Method method = l.getClass().getDeclaredMethod("add",Object.class); method.invoke(l,"test"); method.invoke(l,100.f); }catch (Exception e) { e.printStackTrace(); } System.out.println("list size is: "+l.size()); for ( Object o: l){ System.out.println(o); }

The results of the run are:

The size of the list is: 3abctest100.0(successfully inserted into ArrayList)

We can see that 100.0 was successfully inserted into the ArrayList, so using the principle of type erasure combined with reflection circumvents the operational restrictions that are not allowed by the compiler in normal development.

About "Java generic erasure is what" the content of this article is introduced here, thank you for reading! I believe everyone has a certain understanding of "Java generic erasure is what" knowledge, if you still want to learn more knowledge, welcome to pay attention to the industry information channel.

Tags: Type code information knowledge compilation principle success specialty content bad thing size byte file is in terminology article result line period phase reflection Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB macOS Shulou Information NVidia Huawei