Java 是否使用存储在变量中的嵌套类实例访问外部类实例?
考虑以下类别:Java 是否使用存储在变量中的嵌套类实例访问外部类实例?,java,nested-class,Java,Nested Class,考虑以下类别: 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从B中访问外部A实例。这很有效,
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从B
中访问外部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);
}
}
}
公共A类{
公共INTA;
公共B级{
公共int b;
公共图书馆主任(其他){
System.out.println(other.A.this.A);//根据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语言中没有定义这样的方法。但是,您可以使用一些反射hack来获取该字段的值
基本上,内部类在名为this$0
的字段中存储对封闭类的引用
现在,使用反射,您可以访问该字段,并获取该字段的任何属性的值:
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
但正如我所说,这只是一个黑客行为。你不想在实际应用程序中编写这样的代码。相反,你应该使用@dashblinkenlight的答案中描述的更干净的方法。很好的解决方法。我现在正在使用它。如果在接下来的一个小时左右没有人从帽子里拿出兔子,我会接受。谢谢!