InstantiationException on simple reflective call to newInstance on a class?
Asked Answered
P

2

11

I have an abstract class A, i.e.

public abstract class A {

    private final Object o;

    public A(Object o) {
        this.o = o;
    }

    public int a() {
        return 0;
    }

    public abstract int b();

}

I have a subclass B, i.e.

public class B extends A {

    public B(Object o) {
        super(o);
    }

    @Override
    public int a() {
        return 1;
    }

    @Override
    public int b() {
        return 2;
    }

}

I am executing the following piece of code:

Constructor c = B.class.getDeclaredConstructor(Object.class);
B b = (B) c.newInstance(new Object());

and getting an InstantiationException on the call to newInstance, more specifically:

java.lang.InstantiationException
    at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:30)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)

I don't know why I'm receiving the exception. I have looked at some other similar questions and seen things about the usage of final variables when calling the super constructor or problems with the abstract nature of the parent class, but I could not find a definitive answer to why this particular situation throws an InstantiationException. Any ideas?

Pyaemia answered 25/10, 2011 at 22:44 Comment(4)
Did you mean to omit extends A?Millimicron
Woops yes sorry, edited.Pyaemia
The code that you pasted works for me: ideone.com/0gCkpMillimicron
Hmmm, stripping it down to the bare bones seems to have gotten rid of the error.Pyaemia
P
36

Are you certain that B is not defined with the abstract keyword? I can reproduce the error if I declare the class as public abstract class B.

Pegasus answered 25/10, 2011 at 23:17 Comment(2)
No, I'm not certain. For some reason I do have B declared as abstract (when it doesn't have any methods to be implemented). I assumed that I didn't so this must be just one of those mental slips. Apologies for the waste of time :/Pyaemia
This was precisely my issue.. thanks for the heads up.Conscionable
Z
2

The newInstance() method actually doesn't take any args -- it only triggers the zero-arg constructor. It will throw InstantiationException if your class doesn't have a constructor with zero parameters.

Zephyrus answered 14/1, 2015 at 19:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.