0

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

}

It throws this stack trace

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 Answers 2

3

Please try

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

}
0
0

As the exception clearly states the problem is that reflection.Derived.<init>() does not exist. This because your Derived class doesn't have any default constructor.

You will need to use:

Class<?> c = this.getClass();
Constructor<?> ctor = c.getConstructor(Integer.class);
ctor.newInstance(intValue);
1
  • I have already test it but it gives same error. java.lang.NoSuchMethodException: reflection.Derived.<init>(java.lang.Integer) 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) Nov 22, 2012 at 7:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.