为什么我在这里得到java.lang.InstantiationException?

Say*_*iss 0 java reflection

我正在学习Java中的反射,我写了一些测试代码:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test  {
    class Base {
        public Base() {}
        public void print(){
            System.out.println("base");
        }
    }

    class Derived extends Base {
        @Override
        public void print() {
            System.out.println("derived");
        }
    }

    public static void main(String args[])
    {
        try {
            Class.forName(Derived.class
                    .getTypeName())
                    .getSuperclass()
                    .getMethod("print", new Class[0])
                    .invoke(Base.class.newInstance());// line 41
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我运行此代码时,我得到:

java.lang.InstantiationException: Test$Base
    at java.lang.Class.newInstance(Class.java:427)
    at Test.main(Test.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.lang.NoSuchMethodException: Test$Base.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.newInstance(Class.java:412)
    ... 6 more
Run Code Online (Sandbox Code Playgroud)

有谁可以告诉我为什么?该类的构造函数basepublic但编译器仍声称无法找到其构造函数.

Sot*_*lis 9

因为Base是一个内部类,所有(*)内部类构造函数隐式声明索引0处的封闭类的形式参数.

(*)非私有内部成员类的构造函数隐式声明表示该类的直接封闭实例的变量(第15.9.2节,第15.9.3节)作为第一个形式参数.

换句话说,它不是无参数构造函数.您需要使用Class#getConstructor(Class[])获取适当的构造函数,然后调用它.

Base instance = Base.class.getConstructor(Test.class).newInstance(new Test());
Class.forName(Derived.class.getTypeName()).getSuperclass().getMethod("print", new Class[0]).invoke(instance);
Run Code Online (Sandbox Code Playgroud)

(所有这些都说内部课程难以使用.)