实例化Java中的通用对象 [英] Instantiating generic objects in Java
问题描述
是否可以像下面的代码片段中那样在Java中实例化通用对象?我知道在C#中是可能的.但是,我还没有在Java中看到类似的机制.
Is it possible to instantiate generic objects in Java as does in the following code fragment? I know that it is possible in C#. But, I haven not seen a similar mechanism yet in Java.
// Let T be a generic type.
T t = new T();
推荐答案
不,由于类型擦除,在Java中不起作用.在执行代码时,代码不知道T
是什么.
No, that doesn't work in Java, due to type erasure. By the time that code is executing, the code doesn't know what T
is.
请参阅 Java泛型FAQ 有关Java泛型的更多信息: )-特别是,请参见类型擦除部分.
See the Java Generics FAQ more more information about Java generics than you ever wanted :) - in particular, see the Type Erasure section.
如果出于这种原因或其他原因需要在执行时知道T
的类型,可以将其存储在Class<T>
中,并将其放入构造函数中:
If you need to know the type of T
at execution time, for this or other reasons, you can store it in a Class<T>
and take it in the constructor:
private Class<T> realTypeOfT;
public Foo(Class<T> clazz) {
realTypeOfT = clazz;
}
然后您可以呼叫newInstance()
等.
这篇关于实例化Java中的通用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!