使用反射在抽象类中创建一个实例 我之前打开了类似的问题。但是现在我通过添加带有 int 参数的构造函数来更改派生类。现在我有并且“没有这样的方法异常”。这是源代码和异常。
public abstract class Base {
public Base(){
this(1);
}
public Base(int i){
super();
}
public Base createInstance() throws Exception{
Class<?> c = this.getClass();
Constructor<?> ctor = c.getConstructor();
return ((Base) ctor.newInstance());
}
public abstract int getValue();
}
public class Derived extends Base{
public Derived(int i) {
super(2);
}
@Override
public int getValue() {
return 10;
}
public static void main(String[] args) {
try {
Base b1=new Derived(2);
Base b2 =b1.createInstance();
System.out.println(b2.getValue());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
它抛出这个堆栈跟踪
java.lang.NoSuchMethodException: reflection.Derived.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
at reflection.Base.createInstance(Base.java:17)
at reflection.Derived.main(Derived.java:18)