简体   繁体   中英

JAVA creating instance of nested static class with reflection

I want to create an instance of nested static class with reflection. I have the following code:

if (Modifier.isStatic(nestedClass.getModifiers())) {
                //TODO - WRITE HERE SOMETHING
 } else {
    ctor = nestedClass.getDeclaredConstructor(outerClass);
    ctor.setAccessible(true);
    testInstance = ctor.newInstance(outerInstance);
 }

but cant figure out what to do within the if statement. Some help or advice would be appreciated. Thanks.

Nested static class doesn't require outer instance, so try doing the same as in else but remove outerClass and outerInstance from constructor's arguments.

ctor = nestedClass.getDeclaredConstructor();//no outer class in argument
ctor.setAccessible(true);
testInstance = ctor.newInstance();//no outer instance in argument

Try something like:

Class<MyClass> nestedClass = MyClass.class;
if (Modifier.isStatic(nestedClass.getModifiers())) {
     MyClass instance = nestedClass.newInstance();
     System.out.println(instance);
}
Output:
MainClass$MyClass@1db9742

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM