为什么会抛出java.lang.InstanceionException?
请看以下代码:为什么会抛出java.lang.InstanceionException?,java,reflection,constructor,inner-classes,Java,Reflection,Constructor,Inner Classes,请看以下代码: 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()); } pub
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.InstanceionException
?毕竟,嵌套类
内部具有空构造函数。有人能解释一下吗?内部类的构造函数中的[implicit]第一个参数是对其封闭类的引用。通过反射调用时,需要明确提供:
private void greetWorld() throws Exception {
System.out.println(Inner.class.getConstructors()[0].newInstance(this));
}
您的类内部需要实例化,一个解决方案是将其声明为静态
static class Inner {
public Inner () {}
public String toString(){
return "HelloWorld";
}
}
javap-c Outer$internal
将解释原因。我想注意到,可能缺少公共默认构造函数,这使得无法通过反射API构建内部实例。您肯定需要处理NoSuchMethodException
异常您确定它会编译吗newInstance
应该在构造函数
实例上调用,而不是类
在那里超越了我自己。。。已编辑并修复。@JBNizet,如果没有公共默认值,它将抛出异常constructor@AndrewTobilko当然但是有一个。