newInstance() with inner classes

六月ゝ 毕业季﹏ 提交于 2019-11-29 06:33:03

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);

A non-static inner class cannot be instantiated without an instance of its parent class.

new NewTest().new one()

The call above will successfully instantiate a one.

Your two is being instantiated without an outer instance, because of the static modifier. It is a static nested class.

See the difference between static nested classes and inner classes: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

You need to make class one static. Non-static nested classes must be instantiated with an instance of the containing class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!