java - 获取参数化类型的 java.lang.Class<T> 对象而不构造 q_uestion 中的类?

标签 java class

我想做这样的事情:

Class<List<String>> targetClass = List<String>.class;

但该构造无法编译。

编译器可以用

Class<List<String>> targetClass;

声明,但编译器不喜欢

List<String>.class

有趣的是,编译器 (1.7) 允许这样做:

Class<List<String>> targetClass = (Class<List<String>>) List.class;

但随后当然会提示不安全的转换。

最佳答案

尽管看起来应该如此,List<String>不是类,因此您无法为此获取类对象。泛型仅用于在编译时进行检查。它们从编译的字节码中删除。

所以,你能做的最好的就是,

Class<List> clz = List.class;

来自 Effective Java,第 2 版,

There are two minor exceptions to the rule that you should not use raw types in new code, both of which stem from the fact that generic type information is erased at runtime (Item 25). You must use raw types in class literals. The specification does not permit the use of parameterized types (though it does permit array types and primitive types) [JLS, 15.8.2]. In other words, List.class, String[].class, and int.class are all legal, but List<String>.class and List<?>.class are not

关于java - 获取参数化类型的 java.lang.Class<T> 对象而不构造 q_uestion 中的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9813294/

相关文章:

java - HTTPClient "main"java.lang.NoSuchFieldError : INSTANCE at org. apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>

java - 如何在 Java 中读取 .xlsx 和 .xls 文件?

c++ - 将 QXmlStreamReader 实例传递给类

class - 看起来我正在实例化这个 SpeechAPI 接口(interface)。这怎么可能?

java - 由于我没有使用所有服务,我可以降低 AWS 依赖项大小吗?

java - 基于 Web 还是基于 PC 的过程控制应用程序?

java - 程序加载太多内容? ( java )

c++构造函数不工作

class - 从 kotlin 中的顶级函数获取类引用

java - 调用字节码类方法,java