java - Java 中的泛型类型删除

标签 java generics type-erasure

代码如下:

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() 吗?

没有。同时 xObject 类型的引用, 实际所指对象是 Integer ,所以在运行时,Integer实现toString叫做。

对于getClass也是一样的.

关于java - Java 中的泛型类型删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33177452/

相关文章:

java - 使用 math.random 方法创建骰子方法

java - 服务器在 Naming.rebind 时中断

java - 在非主键列上使用 Hibernate Criteria 进行内部连接

c# - 有没有办法指定 where T :new() restriction but with internal constructor?

c# - 类型删除 : Java vs C#

java - Spring MVC Hibernate 没有具有可用于当前线程的实际事务的 EntityManager - 无法可靠地处理 'persist' 调用

java - Collections 实用程序类中排序函数的实现比较

c# - foreach 与 someList.ForEach(){}

java - 强制转换 "type-erased"对象安全吗?

c++ - 使用函数指针进行类型删除不适用于 GCC