gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:43:08 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com