JAVA 使用反射创建嵌套静态实例 class

JAVA creating instance of nested static class with reflection

我想用反射创建 nested static class 的实例。 我有以下代码:

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

但无法弄清楚在 if 语句中要做什么。 一些帮助或建议将不胜感激。 谢谢

试试这样的东西:

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

嵌套静态 class 不需要外部实例,因此请尝试与 else 中的操作相同,但从构造函数的参数中删除 outerClassouterInstance

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