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.

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

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

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

    public MyClass() {
        Type t = getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) t;
        type = (Class) pt.getActualTypeArguments()[0];
    }

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

In this example, the MyClass class has a generic type parameter T, and the createInstance() method creates an instance of T using the newInstance() method of the Class class.

To use the MyClass class, you can create a subclass that specifies a concrete type for T, like this:

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 the newInstance() method requires a default constructor, so the class that 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 a java.lang.InstantiationException at runtime.