首頁  >  文章  >  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