1

Is it possible to instantiate the class that is provided as generic type parameter in an abstract class?

Example:

public MyClass {
    public MyClass(String test) {

    }
}

Is it possible to instantiate this class inside another abstract class?

public abstract class AbstractClass<T extends MyClass> {
    public AbstractClass() {
        T t = new T("test"); //Cannot instantiate the type T
    }
}
membersound
  • 81,582
  • 193
  • 585
  • 1,120

1 Answers1

5

It's not that straight-forward.

You need a Class<T> that will hold the generic type after type erasure.

Then, you have to invoke Class#getDeclaredConstructor(Class< ? > .. params) to trigger the desired constructor and create new instance dynamically. For example:

public abstract class AbstractClass<T extends MyClass> {
    public AbstractClass(Class<T> clazz) {
        T t = clazz.getDeclaredConstructor(String.class).newInstance("test");
    }
}
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147