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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.