简体   繁体   English

在Java中实例化通用对象

[英]Instantiating generic objects in Java

Is it possible to instantiate generic objects in Java as does in the following code fragment? 是否可以像在下面的代码片段中一样在Java中实例化通用对象? I know that it is possible in C#. 我知道在C#中它是可能的。 But, I haven not seen a similar mechanism yet in Java. 但是,我还没有在Java中看到类似的机制。

// Let T be a generic type.
T t = new T();

No, that doesn't work in Java, due to type erasure. 不,由于类型擦除,这在Java中不起作用。 By the time that code is executing, the code doesn't know what T is. 到代码执行时,代码不知道T是什么。

See the Java Generics FAQ more more information about Java generics than you ever wanted :) - in particular, see the Type Erasure section. 请参阅Java Generics FAQ,了解有关Java泛型的更多信息:) - 特别参见Type Erasure部分。

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: 如果您需要在执行时知道T的类型,由于这个或其他原因,您可以将它存储在Class<T>并将其置于构造函数中:

private Class<T> realTypeOfT;

public Foo(Class<T> clazz) {
  realTypeOfT = clazz;
}

You can then call newInstance() etc. 然后,您可以调用newInstance()等。

I'm afraid not. 恐怕不是。 Generic types in Java are erased - they're used at compile time, but aren't there at runtime (this is actually quite handy in places). Java中的泛型类型被删除 - 它们在编译时使用,但在运行时不存在(这在某些地方实际上非常方便)。

What you can do is to create a new instance from the Class object. 您可以做的是从Class对象创建一个新实例。

Class<T> myClass;
T t = myClass.newInstance();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM