首页 > Java > java教程 > 正文

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

Susan Sarandon
发布: 2024-10-27 00:37:03
原创
243 人浏览过

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!