Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InstantiationException on simple reflective call to newInstance on a class?

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?

like image 682
mburke13 Avatar asked Oct 25 '11 22:10

mburke13


People also ask

How to fix Java lang InstantiationException?

How to Resolve InstantiationException. To avoid the InstantiationException , it should be ensured that the instance of the class that is attempted to be created at runtime using Class. newInstance() is a concrete class and not an abstract class, interface, array class, primitive or void.

What is Java reflection?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

What is Instantiation error in Java?

Class InstantiationErrorThrown when an application tries to use the Java new construct to instantiate an abstract class or an interface. Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.


2 Answers

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.

like image 66
Brett Kail Avatar answered Oct 06 '22 08:10

Brett Kail


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.

like image 21
enkiv2 Avatar answered Oct 06 '22 08:10

enkiv2