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

如何在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)
    ...

我错过了什么?


慕哥9229398
浏览 852回答 2
2回答

GCT1015

还有一个额外的“隐藏”参数,它是封闭类的实例。您需要使用构造函数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 {&nbsp; &nbsp; &nbsp;public static class Child {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void doStuff() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;}}

鸿蒙传说

此代码创建内部类实例。&nbsp;&nbsp;Class&nbsp;childClass&nbsp;=&nbsp;Child.class; &nbsp;&nbsp;String&nbsp;motherClassName&nbsp;=&nbsp;childClass.getCanonicalName().subSequence(0,&nbsp;childClass.getCanonicalName().length()&nbsp;-&nbsp;childClass.getSimpleName().length()&nbsp;-&nbsp;1).toString(); &nbsp;&nbsp;Class&nbsp;motherClassType&nbsp;=&nbsp;Class.forName(motherClassName)&nbsp;; &nbsp;&nbsp;Mother&nbsp;mother&nbsp;=&nbsp;motherClassType.newInstance() &nbsp;&nbsp;Child&nbsp;child&nbsp;=&nbsp;childClass.getConstructor(new&nbsp;Class[]{motherClassType}).newInstance(new&nbsp;Object[]{mother});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java