Is it possible to create an instance of a derived class in abstract ancestor class using reflection
Lets say:
abstract class Base {
public Base createInstance(){
//using reflection
Class<?> c = this.getClass();
Constructor<?> ctor = c.getConstructor();
return ((Base) ctor.newInstance());
}
}//end Base
class Derived extends Base {
main(){
new Derived().createInstance()
}
}
You can do this
prints
A more common pattern is to use Cloneable
prints
However, the need to use either should be avoided. Usually there is another way to do what you need so that base doesn’t not implicitly depend on derived.