【问题标题】:Create an instance within Abstract Class using Reflection-with constructor parameter使用 Reflection-with 构造函数参数在抽象类中创建一个实例
【发布时间】:2012-11-22 07:05:45
【问题描述】:

Create an instance within Abstract Class using Reflection 我之前打开了类似的问题。但是现在我通过添加带有 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)

【问题讨论】:

    标签: java reflection abstract-class


    【解决方案1】:

    请尝试

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

    【讨论】:

      【解决方案2】:

      正如异常明确指出的那样,问题是reflection.Derived.&lt;init&gt;() 不存在。这是因为您的 Derived 类没有任何默认构造函数。

      你需要使用:

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

      【讨论】:

      • 我已经对其进行了测试,但它给出了同样的错误。 java.lang.NoSuchMethodException:reflection.Derived.(java.lang.Integer) at java.lang.Class.getConstructor0(Unknown Source) at java.lang.Class.getConstructor(Unknown Source) atreflection.Base.createInstance (Base.java:17) 在反射.Derived.main(Derived.java:18)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 2019-12-06
      相关资源
      最近更新 更多