0

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.

1
  • Just call the constructor - Class.newInstance. Commented Jan 3, 2015 at 12:29

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Thx. But, if the nestedClass is also private i get an exception. any way around it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.