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

标签 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();
        }
    }
}

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

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

谁能告诉我这是为什么吗?类的构造函数basepublic但编译器仍然声称找不到它的构造函数..

最佳答案

因为Base是一个内部类并且all (*) inner class constructors implicitly declare a formal parameter of the enclosing class at index 0.

The constructor of a (*) non-private inner member class implicitly declares, as the first formal parameter, a variable representing the immediately enclosing instance of the class (§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);

(所有这些都表明内部类很难使用。)

关于java - 为什么我在这里得到 java.lang.InstantiationException ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31396758/

相关文章:

C# 运行时类创建

加载 DLL 期间出现 C# 异常。找不到解决方法

java - Spring Batch 作业随机抛出 FAILED 和 COMPLETED 之间的不同退出状态

java - 在异步 Thrift 客户端中传递 URI/上下文路径

java - 垃圾收集器如何快速知道哪些对象不再有对它们的引用?

java - ReSTLet 响应 POST 请求

c# - 如何将对象转换为列表

c# - 递归例程获取PropertyInfo

c# - 获取具有给定返回类型的所有方法

java - 使用 GUI 的基于文本的冒险游戏存在无法通过按钮继续操作的问题