68

我尝试实例化以下 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)
    ...

我错过了什么?

4

2 回答 2

129

还有一个额外的“隐藏”参数,它是封闭类的实例。您需要使用构造函数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() {
              // ...
          }
     }
}
于 2013-07-05T09:18:09.813 回答
-2

此代码创建内部类实例。

  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});
于 2017-06-17T06:29:33.037 回答