Wash in detail?

I am learning generics in Java. I learned that during compilation, erasing erases all the general information.

Here I learned that all T is replaced by Object.

Integer v = display(2); String d = display("3"); public <T> T display(T i){ return i; } 

I hope he turns into

 Integer v = (Integer)display(2); String d = (String) display("3"); public Object display(Object i){ return i; } 

So, is my assumption true?

Thanks.

+4
source share
3 answers

You basically have this. The compiler uses common parameter types to verify the code, but the generated bytecode replaces another class.

For an unrelated common parameter such as <T> , this will be Object . However, if the declaration was <T extends Comparable> , the replaced class would be Comparable instead of Object .

Edit : Excellent Java Generics information, albeit very dense with piecemeal information:

Java Generics Frequently Asked Questions - Frequently Asked Questions
http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html

+4
source

information about the generic type is not stored in the compiled class; it is used only at compile time to check the type's security.

 Integer v = display(2); 

The Java compiler knows that this method is β€œgeneral”, and it returns the same type as its argument, in this case it is Integer, and the result is assigned to Integer, so everything is fine.

 String d = display("3"); 

completely the same trick. But in this case:

 Long v = display(2); 

Java will tell you that it cannot use, because 2 must be Integer, and Java cannot give it Long, so you need to write:

 Long v = display(2L); 

As I said, no information is stored in the compiled class, so potentially at runtime you can enter a List<Integer> value of type String , and no exception will be thrown, but when you read this String and try to assign a variable of type Integer , you get it ... Well, pretty hard;)

+1
source

I guess, yes. Generics in Java is a good compiler.

0
source

Source: https://habr.com/ru/post/1336348/


All Articles