【问题标题】:JAVA creating instance of nested static class with reflectionJAVA用反射创建嵌套静态类的实例
【发布时间】:2015-03-01 12:48:32
【问题描述】:

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

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

但不知道在 if 语句中要做什么。 一些帮助或建议将不胜感激。 谢谢。

【问题讨论】:

  • 只需调用构造函数 - Class.newInstance

标签: java reflection nested-class static-classes


【解决方案1】:

尝试类似:

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

【讨论】:

  • 谢谢。但是,如果 nestedClass 也是私有的,我会得到一个例外。有什么办法吗?
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    相关资源
    最近更新 更多