java 对类上的 newInstance 进行简单反射调用时的 InstantiationException?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7896773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:53:34  来源:igfitidea点击:

InstantiationException on simple reflective call to newInstance on a class?

javareflectioninstantiationexception

提问by mburke13

I have an abstract class A, i.e.

我有一个抽象类A,即

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.

我有一个子类 B,即

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:

并在调用 newInstance 时获得 InstantiationException,更具体地说:

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?

我不知道为什么我会收到异常。我查看了其他一些类似的问题,并了解了调用超级构造函数时最终变量的使用或父类的抽象性质的问题,但我找不到关于为什么这种特殊情况会引发 InstantiationException 的明确答案。有任何想法吗?

回答by Brett Kail

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

你确定 B 没有用abstract关键字定义?如果我将类声明为public abstract class B.

回答by enkiv2

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.

newInstance() 方法实际上不接受任何参数——它只触发零参数构造函数。如果您的类没有带零参数的构造函数,它将抛出 InstantiationException。