Instantiating generic objects in Java

generics, java

Solution

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.

Problem

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

Original source

Related problems