开发者

Erasure in detail?

开发者 https://www.devze.com 2023-02-06 00:39 出处:网络
I am studying generics in Java. I studied that during compilation, erasure erases all the generic info.

I am studying generics in Java. I studied that during compilation, erasure erases all the generic info.

Here, i studied that all T is replaced with Object.

 Integer v = display(2);
 String d = display("3");

pub开发者_Python百科lic <T> T display(T i){
       return i;
    }

I hope it will be turn into

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

So, is my assumption right?

Thanks.


You basically have it. The compiler uses the generic parameter types to validate the code, but the generated bytecode substitutes in a different class.

For an unbound generic parameter like <T>, it would be Object. However, if the declaration were <T extends Comparable>, the substituted class would be Comparable instead of Object.

Edit: Great info about Java Generics, albeit really dense with info in parts:

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


information about generic type is not saved into compiled class, it is used only at compile time to check type safety.

Integer v = display(2);

Java compiler knows that that method is "generic", and it returns the same type as its argument, in this case it is Integer, and result is assigned to Integer, so everything is ok.

String d = display("3");

totally the same trick. But in that case:

Long v = display(2);

Java will tell you that it can't cast, because 2 is meant to be Integer, and Java can't cast it to Long, so you need to write:

Long v = display(2L);

As I told, no information is saved into compiled class, so potentially during runtime time you can put into the List<Integer> value of String type, and no exception will be thrown, but when you read this String and try to assign to Integer type variable you will get it... Well, quite tricky ;)


Basically, yes. Generics in Java is a nice compiler trick.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号