我想做这样的事情:
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
, andint.class
are all legal, butList<String>.class
andList<?>.class
are not
关于java - 获取参数化类型的 java.lang.Class<T> 对象而不构造 q_uestion 中的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9813294/