繁体   English   中英

如何在Java中使用反射实例化内部类?

[英]How to instantiate an inner class with reflection in Java?

我尝试实例化以下Java代码中定义的内部类:

 public class Mother {
      public class Child {
          public void doStuff() {
              // ...
          }
      }
 }

当我尝试获取像这样的Child的实例时

 Class<?> clazz= Class.forName("com.mycompany.Mother$Child");
 Child c = clazz.newInstance();

我得到这个例外:

 java.lang.InstantiationException: com.mycompany.Mother$Child
    at java.lang.Class.newInstance0(Class.java:340)
    at java.lang.Class.newInstance(Class.java:308)
    ...

我想念什么?

还有一个额外的“隐藏”参数,它是封闭类的实例。 您需要使用Class.getDeclaredConstructor到达构造函数,然后提供封闭类的实例作为参数。 例如:

// All exception handling omitted!
Class<?> enclosingClass = Class.forName("com.mycompany.Mother");
Object enclosingInstance = enclosingClass.newInstance();

Class<?> innerClass = Class.forName("com.mycompany.Mother$Child");
Constructor<?> ctor = innerClass.getDeclaredConstructor(enclosingClass);

Object innerInstance = ctor.newInstance(enclosingInstance);

编辑:或者,如果嵌套类实际上不需要引用封闭实例,则使其成为嵌套静态类:

public class Mother {
     public static class Child {
          public void doStuff() {
              // ...
          }
     }
}

这段代码创建内部类实例。

  Class childClass = Child.class;
  String motherClassName = childClass.getCanonicalName().subSequence(0, childClass.getCanonicalName().length() - childClass.getSimpleName().length() - 1).toString();
  Class motherClassType = Class.forName(motherClassName) ;
  Mother mother = motherClassType.newInstance()
  Child child = childClass.getConstructor(new Class[]{motherClassType}).newInstance(new Object[]{mother});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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