如何在Java中使用MyClass< String> .class`? [英] How to do `MyClass<String>.class` in Java?
问题描述
如何调用 编辑:'David Winslow'和'bmargulies'的回应是正确的 使用 如果要使用Class对象(例如)实例化新的List实例,可以将该操作的结果转换为具有适当的类型参数。 How can call EDIT: 'David Winslow' and 'bmargulies' responses are correct Edit: I have replaced List with MyClass and added the condition to my original question. Use If you want to use the Class object to (for example) instantiate a new List instance, you can cast the result of that operation to have the appropriate type parameter.
这篇关于如何在Java中使用MyClass< String> .class`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! public< T>使用
MyClass< String> .class
作为clazz,在这里我不能实例化或扩展MyClass。 p>
(MyClass< String>)doit(MyClass.class);
适用于原始问题,但令人惊讶的是,当方法返回 MyClass< T>
而不是 T
编辑:我已经用MyClass代替了List,并将条件添加到了我原来的问题中。 List.class
。因为Java类的类型擦除类型参数完全是一个编译-time构造 - 即使 List< String> .class
是有效的语法,它应该是完全相同的类与 List< Date> .class
等等。由于反射在本质上是一种运行时事物,它不能很好地处理类型参数(如在Java中实现的那样)。
列表< String> list =(List< String>)(ArrayList.class.newInstance());
public <T> T doit(Class<T> clazz);
using MyClass<String>.class
as clazz where I can not instantiate or extend MyClass.(MyClass<String>) doit(MyClass.class);
works for the original question BUT surprisingly when the method returns say MyClass<T>
instead of T
casting will not compile any more.List.class
. Because of type erasure type parameters to Java classes are entirely a compile-time construct - even if List<String>.class
was valid syntax, it would be the exact same class as List<Date>.class
, etc. Since reflection is by nature a runtime thing, it doesn't deal well with type parameters (as implemented in Java).List<String> list = (List<String>)(ArrayList.class.newInstance());