考虑以下类:
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.this
从 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);
}
}
}
从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 - 使用存储在变量中的嵌套类实例访问外部类实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22330500/