簡體   English   中英

使用存儲在變量中的嵌套類實例訪問外部類實例?

[英]Access outer class instance using nested class instance stored in a variable?

考慮以下類別:

public class A {
    public int a;

    public class B {
         public int b;

         public void foo() {
             System.out.println(A.this.a);
             System.out.println(this.b);
         }
    }
}

foo ,我使用語法A.thisB內部訪問外部A實例。 這很好,因為我試圖從B的“當前對象”訪問A的外部實例。 但是,如果我想從類型B變量訪問外部A對象,該怎么辦?

public class A {
    public int a;

    public class B {
         public int b;

         public void foo(B other) {
             System.out.println(other.A.this.a); // <-- This is (obviously) wrong. What SHOULD I do here?
             System.out.println(other.b);
         }
    }
}

foo other “內部”實例訪問“外部”實例的正確語法是什么?

我意識到我可以使用other.a來訪問外部變量a 請原諒人為的例子! 我只是想不出一種更好的方法來詢問如何到達other.A.this

據我從Java語言規范中了解到的,Java沒有提供這種訪問的語法。 您可以通過提供自己的訪問器方法來解決此問題:

public class A {
    public int a;

    public class B {
         public int b;
         // Publish your own accessor
         A enclosing() {
             return A.this;
         }
         public void foo(B other) {
             System.out.println(other.enclosing().a);
             System.out.println(other.b);
         }
    }
}

嗯,您不能直接執行此操作,因為Java語言中沒有定義這種方法。 但是,您可以使用一些反射技巧來獲取該字段的值。

基本上,內部類將對封閉類的引用存儲在名為this$0的字段中。 您可以在有關SO的另一篇文章中找到更多詳細信息

現在,使用反射,您可以訪問該字段,並獲取該字段的任何屬性的值:

class A {
    public int a;

    public A(int a) { this.a = a; }

    public class B {
         public int b;

         public B(int b) { this.b = b; }

         public void foo(B other) throws Exception {
             A otherA = (A) getClass().getDeclaredField("this$0").get(other); 
             System.out.println(otherA.a);
             System.out.println(other.b);
         }
    }
}

public static void main (String [] args) throws Exception {
    A.B obj1 = new A(1).new B(1);
    A.B obj2 = new A(2).new B(2);
    obj2.foo(obj1);
}

這將打印1, 1

但是正如我所說,這只是一個hack。 您不想在實際應用程序中編寫這樣的代碼。 相反,您應該采用@dashblinkenlight答案中所描述的更干凈的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM