简体   繁体   中英

Instantiating generic objects in 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();

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.

See the Java Generics FAQ more more information about Java generics than you ever wanted :) - in particular, see the Type Erasure section.

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;
}

You can then call newInstance() etc.

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).

What you can do is to create a new instance from the Class object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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