首页  >  文章  >  Java  >  如何在没有外围类实例的情况下使用 Java 反射实例化内部类?

如何在没有外围类实例的情况下使用 Java 反射实例化内部类?

Susan Sarandon
Susan Sarandon原创
2024-10-27 00:37:03234浏览

How Can You Instantiate an Inner Class Using Java Reflection Without an Instance of the Enclosing Class?

使用 Java 反射实例化内部类

在 Java 中,尝试使用反射实例化内部类而不提供封闭类的实例将会导致 InstantiationException。发生这种情况是因为内部类对其封闭类实例具有隐藏的依赖关系。

解决方案:

要解决此问题,请使用 Class. 检索内部类的构造函数。 getDeclaredConstructor 并在实例化时将封闭类的实例作为参数传递。

示例:

<code class="java">// Assuming "com.mycompany.Mother" is the enclosing class
// and "com.mycompany.Mother$Child" is the inner class

// Get the enclosing class
Class<?> enclosingClass = Class.forName("com.mycompany.Mother");
// Instantiate the enclosing class
Object enclosingInstance = enclosingClass.newInstance();

// Get the inner class
Class<?> innerClass = Class.forName("com.mycompany.Mother$Child");
// Get the constructor with the enclosing class as a parameter
Constructor<?> ctor = innerClass.getDeclaredConstructor(enclosingClass);

// Instantiate the inner class
Object innerInstance = ctor.newInstance(enclosingInstance);</code>

替代方法:

如果内部类不需要访问封闭类实例,则可以将其定义为静态嵌套类。这消除了对封闭类的依赖。

静态嵌套类的示例:

<code class="java">public class Mother {
     public static class Child {
          public void doStuff() {
              // ...
          }
     }
}</code>

以上是如何在没有外围类实例的情况下使用 Java 反射实例化内部类?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn