Java – instantiationexception calls a class on newinstance for simple reflection?

I have an abstract class A, which is

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, namely

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 code:

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

And the call to newinstance gets an instantiationexception, 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 received an exception I have looked at some other similar questions, and used the final variable when calling the super constructor or saw the abstract properties of the parent class, but I can't find the exact answer to why this special case caused an instantiationexception Any ideas?

Solution

Are you sure that B does not define abstract keywords? If I declare the class as public abstract class B, I can reproduce the error

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>