I would like to be able to create a new instance of a class when it's in a variable whose type is abstract.
class Scratch {
public static void main(String[] args) {
Implementation implementation = new Implementation();
// ...Later in the code Implementation is abstracted away and it's AbstractClass
AbstractClass implementedAbstractClass = implementation;
AbstractClass newInstance = implementedAbstractClass.newInstance();
}
}
abstract class AbstractClass {
protected abstract AbstractClass createNewInstance();
public AbstractClass newInstance() {
return createNewInstance();
}
}
class Implementation extends AbstractClass {
@Override
protected AbstractClass createNewInstance() {
return new Implementation();
}
}
This works, but I would like to avoid the boiler plate of having to implement createNewInstance()
in every implementation I make.
I tried changing AbstractClass
to accept a type parameter: AbstractClass<T extends AbstractClass<T>>
, then Implementation extends AbstractClass<Implementation>
and then calling new T()
but of course that doesn't work either because Java doesn't know what T
is at compile time so it can't add a construct instruction into the class file.
Afterwards I tried calling AbstractClass.class.getDeclaredConstructor().newInstance()
but that made even less sense since I'd just be attemping to construct an instance of AbstractClass which isn't possible since it's abstract nor is it what I needed.