【发布时间】:2014-10-27 09:02:52
【问题描述】:
我一直在研究一种实例化方法,该方法允许我将各种类似的类打包到一个外部类中。然后我可以通过将该类型的名称传递给构造函数来实例化每个唯一的类类型。经过大量的研究和错误,这就是我想出的。我留下了一个错误,以证明我的问题。
import java.lang.reflect.Constructor;
public class NewTest
{
public static void main(String[] args)
{
try
{
Class toRun = Class.forName("NewTest$" + args[0]);
toRun.getConstructor().newInstance();
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
public NewTest(){}
private class one //Does not instantiate
{
public one()
{
System.out.println("Test1");
}
}
private static class two //Instantiates okay
{
public two()
{
System.out.println("Test2");
}
}
}
编译此代码并运行java NewTest two 会得到Test2 的输出,如我所愿。
运行 java NewTest one 结果
java.lang.NoSuchMethodException: NewTest$one.<init>()
at java.lang.Class.getConstructor(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
at NewTest.main(NewTest.java:12)
我对此感到困惑,因为据我所知,我正确地引用了内部类,外部类应该可以访问内部类,并且我有一个默认的无参数构造函数。
【问题讨论】:
-
一个不是静态的,需要在newtest的实例中实例化。
-
所以,我必须这样做
NewTest parent = new NewTest();和parent.toRun.getConstructor().newInstance()? -
@NonSecwitter 不,
parent.toRun将不可编译。 Java 在new上用于创建内部类实例的特殊语法不适用于newInstance,它只是具有任何其他方法调用的语法。 -
javadoc for
getConstructor说:“如果此 Class 对象表示在非静态上下文中声明的内部类,则形式参数类型包括显式封闭实例作为第一个参数。” Simone 的回答使用了这个信息。 -
啊。我读了,直到现在我才明白。我还在习惯行话:/
标签: java reflection instantiation inner-classes