W3docs

Create instance of generic type in Java?

To create an instance of a generic type in Java, you can use the newInstance() method of the Class class, along with the Type and TypeVariable classes.

To create an instance of a generic type in Java, you can use reflection to capture the type parameter at runtime. Due to type erasure, the class must be extended to preserve generic type information. You can then instantiate the type using getDeclaredConstructor().newInstance().

Here is an example of how you can create an instance of a generic type:


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class MyClass<T> {
    private final Class<T> type;

    public MyClass() {
        Type t = getClass().getGenericSuperclass();
        if (!(t instanceof ParameterizedType)) {
            throw new IllegalStateException("MyClass must be extended to preserve generic type information.");
        }
        ParameterizedType pt = (ParameterizedType) t;
        type = (Class<T>) pt.getActualTypeArguments()[0];
    }

    public T createInstance() throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        return type.getDeclaredConstructor().newInstance();
    }
}

In this example, MyClass captures the generic type parameter T from its superclass. The createInstance() method creates an instance of T using the modern reflection API.

To use MyClass, you must create a subclass that specifies a concrete type for T. This preserves the type information at runtime, which would otherwise be erased by the compiler.


public class MySubClass extends MyClass<String> {
}

MySubClass subClass = new MySubClass();
String s = subClass.createInstance();  // s is a new instance of String

Keep in mind that getDeclaredConstructor().newInstance() requires a default constructor, so the class you are trying to instantiate must have a public or default (package-private) no-arg constructor. If the class does not have a suitable constructor, you will get an InstantiationException or NoSuchMethodException at runtime.