Is it possible to create an instance of a derived class in abstract ancestor class using reflection Lets say:
abstract class Base {
public Base createInstan
You can do this
public class Derived extends Base {
public static void main(String ... args) {
System.out.println(new Derived().createInstance());
}
}
abstract class Base {
public Base createInstance() {
//using reflection
try {
return getClass().asSubclass(Base.class).newInstance();
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
prints
Derived@55fe910c
A more common pattern is to use Cloneable
public class Derived extends Base {
public static void main(String ... args) throws CloneNotSupportedException {
System.out.println(new Derived().clone());
}
}
abstract class Base implements Cloneable {
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
prints
Derived@8071a97
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.