为什么抛出java.lang.InstantiationException?

use*_*082 3 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());
    }

    public class Inner {
        public Inner () {}
        public String toString(){
            return "HelloWorld";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它为什么被抛出java.lang.InstantiationException
毕竟,嵌套类Inner有nully构造函数.有人可以解释一下吗?

Mur*_*nik 6

内部类的构造函数中的[隐含]第一个参数是对其封闭类的引用.通过反射调用它时,您需要明确地提供它:

private void greetWorld() throws Exception {
    System.out.println(Inner.class.getConstructors()[0].newInstance(this));
}
Run Code Online (Sandbox Code Playgroud)

  • 你确定它会编译吗?应该在`Constructor`实例上调用`newInstance`,而不是`Class` (2认同)