【问题标题】:Why I get java.lang.InstantiationException here? [duplicate]为什么我在这里得到 java.lang.InstantiationException? [复制]
【发布时间】:2015-07-14 02:42:56
【问题描述】:

我正在学习 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

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

【问题讨论】:

  • 我认为这是因为Base 是实例类,没有Test 的实例就无法创建它...我认为...如果您将Base 和static内部类,它会工作
  • 看看this question/answer 使用反射实例化内部实例类的解决方案...

标签: java reflection


【解决方案1】:

因为Base 是一个内部类,而all (*) inner class constructors implicitly declare a formal parameter of the enclosing class at index 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);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-31
    • 2021-11-08
    • 2016-11-22
    • 2015-10-25
    • 1970-01-01
    • 2016-09-26
    • 2012-03-13
    • 1970-01-01
    相关资源
    最近更新 更多