非静态内部类newInstance

https://stackoverflow.com/questions/25634542/newinstance-with-inner-classes

 

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

 

public HttpServerJob setModifier(Class<? extends Modifier> modifier) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Constructor<?> ctor = modifier.getDeclaredConstructor(HttpServerJob.class);
ctor.setAccessible(true);
this.modifier = (Modifier)ctor.newInstance(this);
return this;
}

 

 

 

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

posted on 2023-07-03 11:17  silyvin  阅读(13)  评论(0编辑  收藏  举报