Search code examples
javareflectionnested-classstatic-classes

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.


Solution

  • 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