tags:

views:

69

answers:

2

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();

Thanks in advance.

+7  A: 

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.

Jon Skeet
+2  A: 

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();
Daniel Winterstein