How Type Erasure work in java?

跟風遠走 提交于 2021-02-08 10:51:05

问题


I was going through TypeErasure topic at http://download.oracle.com/javase/tutorial/java/generics/erasure.html which says that compiler removes all information related to type parameters and type arguments within a class or method.

Now considering the code below

public class Box<T> {
    private T t; // lineA, T stands for "Type" 

    public void add(T t) { // lineB
        this.t = t; // lineC
    }

    public T get() { // lineD
        return t; // lineE
    }
}

Now inside main method I have below code snippet

Box<String> box1 = new Box<String>(); // line1
box1.add("Scott"); // line2
String s1tr=box1.get(); // line3

Box<Integer> box2 = new Box<Integer>(); // line4
box2.add(1); // line5
Integer k=box2.get(); // line6

Now in above code (in Box class and main method) what are the changes compiler will make and at which line?

As the link says that compiler removes all information related to type parameters and type arguments within a class or method, when compiler will compile Box class, will it remove all T,<String>,<Integer> occurences from Box class and main method respectively? If yes, what will be the compiled code after Removing T?


回答1:


Type erasure happens at compile time. Java compiler removes those generic type information from source and adds casts as needed and delivers the byte code. Therefore the generated byte code will not have any information about type parameters and arguments. It will look like a old java code without generics. There is no way to determine the value of T at runtime, because that information is removed before the code is compiled.




回答2:


In the absence of type bounds like in your example code, what will (roughly) happen that in the Box class, all instances of all references to T in method code will be replaced by Object. In the code using the Box class, all instances of <String>, <Integer> and such will be removed.

An exhaustive in-depth article on Java Generics is Angelika Langer's FAQ - it also explains the effect of type bounds and a lot more.



来源:https://stackoverflow.com/questions/7371433/how-type-erasure-work-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!