How to make a new Object of type T

generics, java

Solution

As Jon commented you explictly need the class due to type erasure.

E.g. if you have a generic method, you'll have to do it like this:

public void <T> myMethod(Class<T> clazz) {
    T foo = clazz.newInstance();
}

If it's a generic class it basically works the same. You just have to pass the class object to the metod or even to the constructor.

Problem

I'm trying to make a new Object of type T. I tried: ``` T h = new T(); T h = T.newInstance(); ``` Those don't work. I also tried: ``` T h = (T)(new Object()); ``` That works, but then `h.getClass().getName()` returns `java.lang.Object` Is there any way to make a default object of this class without knowing the class name? EDIT (from comments): `T` is a generic. Like `Class<T>`.

Original source

Related problems