本文介绍了如何在Java中使用反射实例化非静态内部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to instantiate the inner class defined in the following Java code:

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

当我试图获得这样的Child实例时

When I try to get an instance of Child like this

 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)
    ...

我缺少什么?

推荐答案

还有一个额外的隐藏参数,它是封闭类的实例。你需要使用然后提供封闭类的实例作为参数。例如:

There's an extra "hidden" parameter, which is the instance of the enclosing class. You'll need to get at the constructor using Class.getDeclaredConstructor and then supply an instance of the enclosing class as an argument. For example:

// 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);

编辑:或者,如果嵌套类实际上不需要引用封闭实例,请make它是一个嵌套的静态类:

Alternatively, if the nested class doesn't actually need to refer to an enclosing instance, make it a nested static class instead:

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

这篇关于如何在Java中使用反射实例化非静态内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:32