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();
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
ovunccetin
  • 8,443
  • 5
  • 42
  • 53
  • 1
    Possible duplicate: http://stackoverflow.com/questions/1090458/instantiating-a-generic-class-in-java – Mike Oct 27 '10 at 13:09

2 Answers2

10

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

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
  • 2,418
  • 1
  • 29
  • 41