代码如下:
public class Main {
public static void main(String[] args) {
Gen<Integer> g = new Gen<Integer>(5);
System.out.println(g.getClass());
System.out.println(g.ob.getClass());
}
}
class Gen<T> {
T ob;
public Gen(T x) {
ob = x;
}
}
这是输出
class Gen // This I understand
class java.lang.Integer // But if type erasure is happening, shouldn't this be java.lang.Object?
我知道类型参数 T
在运行时被删除,但为什么 ob
的类型参数在运行时仍然存在?
最佳答案
不!
考虑一下:
Object x = new Integer(1);
System.out.println(x.toString());
你会得到 1
.
但我不应该得到 Object.toString() 吗?
没有。同时 x
是 Object
类型的引用, 实际所指对象是 Integer
,所以在运行时,Integer
实现toString
叫做。
对于getClass
也是一样的.
关于java - Java 中的泛型类型删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33177452/