使用Reflection-with构造函数参数在Abstract Class中创建实例 [英] Create an instance within Abstract Class using Reflection-with constructor parameter
本文介绍了使用Reflection-with构造函数参数在Abstract Class中创建实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用反射在抽象类中创建实例
我之前也提出过类似的问题。但是现在我通过添加带有int参数的构造函数来更改了Derived类。现在,我遇到了没有这种方法异常的问题。这是源代码和异常。
Create an instance within Abstract Class using Reflection I opened similar question before. But now I have changed the Derived class by adding constructor with int parameter. And now I am having and "no such method exception". here is the source code and exception.
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)
推荐答案
请尝试
import java.lang.reflect.Constructor;
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(new Class[] { int.class });
return ((Base) ctor.newInstance(new Object[] { 1 }));
}
public abstract int getValue();
}
这篇关于使用Reflection-with构造函数参数在Abstract Class中创建实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文