Java 类型信息 —— 获取泛型类型的类对象(.class)

How to get a class instance of generics type T

考虑泛型类Foo<T>,在其成员中,如果想获取类型(type)T的类实例(class instance of type T),是不可以直接调用 T.class的。原因在于,Java 语言无法获取泛型类型参数(T)的运行时信息(不可以直接调用 T.class)。

0. 常用解决方案

既然无法调用泛型类型参数的运行时类型信息,便在调用端,显示地传递该类的运行时类型信息进去(通过构造函数),一种惯用的解决方案如下:

class Foo<T> {
    private final Class<T> type;
    public Foo<T>(Class<T> type) {
        this.type = type;
    }
    public static void main(String[] args) {
        // 在客户端调用时,便会显得有些啰嗦
        Foo<SomeClass> f = new Foo<SomeClass>(SomeClass.class);
    }
}

1. Pure Java solution

原文地址:https://www.cnblogs.com/mtcnn/p/9421204.html