使用Reflection-with构造函数参数在Abstract Class中创建实例

时间:2012-11-22 07:05:46

标签: java reflection abstract-class

Create an instance within Abstract Class using Reflection 我之前打过类似的问题。但是现在我通过使用int参数添加构造函数来更改Derived类。现在我正在和“没有这样的方法例外”。这是源代码和例外。

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)

2 个答案:

答案 0 :(得分:3)

请尝试

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

}

答案 1 :(得分:0)

由于例外明确指出问题是reflection.Derived.<init>()不存在。这是因为您的Derived类没有任何默认构造函数。

您需要使用:

Class<?> c = this.getClass();
Constructor<?> ctor = c.getConstructor(Integer.class);
ctor.newInstance(intValue);