带有内部类的newInstance() [英] newInstance() with inner classes
问题描述
我一直在研究一种实例化方法,它允许我将各种类似的类打包到一个外部类中。然后,我可以通过将该类型的名称传递给构造函数来实例化每个唯一的类类型。经过大量的研究和错误,这就是我想出的。我留下了一个错误,以证明我的问题。
I've been working on an instantiation method that will allow me to package a variety of similar classes into one outer class. I could then instantiate each unique class type by passing the name of that type to the constructor. After a lot of research and errors, this is what I have come up with. I have left an error, to demonstrate my question.
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两个
导致输出 Test2
,如我所愿。
Compiling this code and running java NewTest two
results in the output Test2
, as I intended.
运行 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)
我对此感到困惑因为,就我而言知道,我正确地引用了一个内部类,外部类应该可以访问内部类,并且我有一个默认的没有arg构造函数。
I'm confused about this because, as far as I know, I am referencing an inner class correctly, an outer class should have access to an inner class, and I have a default no arg constructor.
推荐答案
非静态内部类需要外部类的实例才能正常工作。所以,他们并没有真正拥有默认构造函数,他们总是有一种隐藏参数,他们期望外部类实例。
Non-static inner classes need an instance of the outer class to work properly. So, they don't "really" have a default constructor, they always have a kind of hidden parameter in which they expect an outer class instance.
我不知道知道为什么你想把它们全部放在一个班级里。如果您这样做只有一个文件,请将它们放在一个包中并放在不同的类中。拥有较少的文件并不能使你的程序更好。
I don't know why you want to have them all in a single class. If you are doing this so that it's only one file, put them in a package and in separate classes. Having less files does not make your program better.
如果你需要它们分享一些东西,那么外层类将作为一种范围工作,你可以仍然不使用内部类,但通过传递它们的某种上下文。
If instead you need them to share something, so the outer class will work as a kind of "scope", you can still do that without using inner classes, but by passing them a context of some sort.
如果你真的想要实例化内部类,你需要使用隐藏将外层类作为参数的构造函数:
If you really really want to instantiate the inner class, you need to use the hidden constructor taking the outer class as a parameter :
NewTest outer = new NewTest();
Class<?> toRun = Class.forName("NewTest$" + args[0]);
Constructor<?> ctor = toRun.getDeclaredConstructor(NewTest.class);
ctor.newInstance(outer);
这篇关于带有内部类的newInstance()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!