Java中的Type Erasure如何工作? [英] How Type Erasure work in java?
问题描述
我正在通过 http://download.oracle上的TypeErasure主题进行浏览..com/javase/tutorial/java/generics/erasure.html 其中说该编译器将删除与类或方法中的类型参数和类型参数有关的所有信息.
现在考虑以下代码
公共类Box< T>{私人T t;//lineA,T代表类型"public void add(T t){//lineBthis.t = t;//lineC}公共T get(){//lineD返回t//lineE}}
现在在 main
方法内部,我有下面的代码片段
Box< String>box1 =新的Box< String>();//第1行box1.add("Scott");//第2行字符串s1tr = box1.get();//第3行Box< Integer>box2 =新的Box< Integer>();//第4行box2.add(1);//第5行整数k = box2.get();//第6行
现在在以上代码中(在 Box
类和 main
方法中),编译器将进行哪些更改以及在哪一行?
正如链接所述,编译器在编译器时会删除与类或方法中的类型参数和类型参数有关的所有信息.将编译 Box
类,它将从中删除所有 T
,< String>
,< Integer>
事件分别是 Box
类和 main
方法?如果是,那么删除 T
之后的编译代码是什么?
类型擦除发生在编译时.Java编译器从源中删除那些泛型类型信息,并根据需要添加强制类型转换并提供字节码.因此,生成的字节码将不包含有关类型参数和参数的任何信息. 它看起来像是没有泛型的旧Java代码. 无法在运行时确定T的值,因为在编译代码之前会删除该信息./p>
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
?
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.
这篇关于Java中的Type Erasure如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!