使用Reflection在Abstract Class中创建实例

Ahm*_*aya 5 java reflection abstract-class

是否可以使用反射在抽象祖先类中创建派生类的实例让我们说:

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()

 }
Run Code Online (Sandbox Code Playgroud)

}

Pet*_*rey 3

你可以这样做

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

印刷

Derived@55fe910c
Run Code Online (Sandbox Code Playgroud)

更常见的模式是使用 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

印刷

Derived@8071a97
Run Code Online (Sandbox Code Playgroud)

然而,应该避免使用其中任何一个。通常还有另一种方法可以完成您需要的操作,以便基类不会隐式依赖于派生类。