我正在试验泛型类,并且遇到了我无法克服的障碍。总之,我遇到了,我不明白为什么它被抛出的错误:InstantiationExceptionJava - 在Class <?上使用newInstance()的泛型类扩展myClass>:InstantiationException
在文档就这个异常定义为:
Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated because it is an interface or is an abstract class.
现在有我抓我的头问题是我不使用抽象或接口关键字。我也听说这可能是由于没有默认的构造函数(我有)。只是可以肯定,我在我的代码减少到最小的可能,但还是给出了一个错误:
package Sandbox;
public class Sandbox {
public static void main(String[] args) {
Sandbox box = new Sandbox();
}
public Sandbox() {
aMethod(subThread.class);
}
public void aMethod(Class<? extends superThread> type) {
try {
System.out.println("isInterface: "+type.isInterface());
System.out.println("isAssignableFrom of subThread: "+type.isAssignableFrom(subThread.class));
superThread t = type.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private class superThread { // implements Runnable {
public superThread() {}
public void run() {}
}
private class subThread extends superThread {
public subThread() {
super();
}
public void run() {
// more stuff
}
}
}
输出:
isInterface: false
isAssignableFrom of subThread: true
java.lang.InstantiationException: Sandbox.Sandbox$subThread
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at Sandbox.Sandbox.aMethod(Sandbox.java:20)
at Sandbox.Sandbox.<init>(Sandbox.java:11)
at Sandbox.Sandbox.main(Sandbox.java:7)
我敢肯定,这很简单,但我不明白这一出。我尝试了几件事,但没有任何帮助。任何和所有的帮助表示赞赏。
感谢, 乔恩
是的,你完全正确。我一直在寻找错误的地方。谢谢。 –
我很确定内部类的访问级别与它无关。事实上,当它们公开时也会发生同样的例外。如果它们是私有静态的,则不会发生异常。 – VGR