如何在Java中使用反射实例化内部类? [英] How to instantiate an inner class with reflection in Java?

查看:450
本文介绍了如何在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)
    ...

我想念什么?

推荐答案

还有一个额外的"hidden"参数,它是封闭类的实例.您需要使用

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

或者,如果嵌套类实际上不需要引用封闭的实例,则改为使其成为嵌套的 static 类:

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中使用反射实例化内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆