对类上的 newInstance 进行简单反射调用时出现 InstantiationException?
我有一个抽象类 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();
}
我有一个子类 B,即
public class B extends A {
public B(Object o) {
super(o);
}
@Override
public int a() {
return 1;
}
@Override
public int b() {
return 2;
}
}
我正在执行以下代码:
Constructor c = B.class.getDeclaredConstructor(Object.class);
B b = (B) c.newInstance(new Object());
并在调用 newInstance 时收到 InstantiationException,更具体地说:
java.lang.InstantiationException
at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:30)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
我不知道为什么收到异常。我查看了其他一些类似的问题,并看到了有关调用超级构造函数时使用最终变量或父类的抽象性质问题的问题,但我找不到关于为什么这种特殊情况会引发 InstantiationException 的明确答案。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您确定 B 不是用
abstract
关键字定义的吗?如果我将该类声明为公共抽象类 B,我可以重现该错误。Are you certain that B is not defined with the
abstract
keyword? I can reproduce the error if I declare the class aspublic abstract class B
.newInstance() 方法实际上不接受任何参数——它只触发零参数构造函数。如果您的类没有零参数的构造函数,它将抛出 InstantiationException。
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.