【发布时间】:2017-11-25 11:53:51
【问题描述】:
看下面的代码:
public class Outer {
public static void main(String[] args) throws Exception {
new Outer().greetWorld();
}
private void greetWorld() throws Exception {
System.out.println(Inner.class.newInstance());
}
public class Inner {
public Inner () {}
public String toString(){
return "HelloWorld";
}
}
}
为什么会抛出java.lang.InstantiationException?
毕竟,嵌套类Inner 具有无效的构造函数。谁能解释一下?
【问题讨论】:
-
javap -c Outer$Inner会解释原因。 -
我想注意到公共默认构造函数可能不存在,这使得通过反射 API 构建内部实例是不可能的。你肯定需要处理
NoSuchMethodException异常
标签: java reflection constructor inner-classes