我在学习的时候就在想这个情况local classes来自 Oracle 的教程:
class HelloWorldApp {
public String s = "string in outer class";
public void shout() {
final String s = "string in enclosing method";
class out {
public String s = "string in local class";
public void show()
{
System.out.println(s);
System.out.println(HelloWorldApp.this.s);//reference the member of enclosing class
System.out.println(HelloWorldApp.this.shout.s)//compiler complaints
}
}
out no = new out();
no.show();
}
public static void main(String[] args) {
HelloWorldApp h = new HelloWorldApp();
h.shout();
}
}
现在,我想在这种情况下引用方法shout()
的局部变量s
,但教程没有给出要点。
我已经通过 Google 和 StackOverflow 进行了搜索,但找不到正确的出路。
最佳答案
你不能。
JLS 6.4 说:
A local variable (§14.4), formal parameter (§8.4.1), exception parameter (§14.20), and local class (§14.3) can only be referred to using a simple name (§6.2), not a qualified name (§6.6).
6.4.1 说:
Some declarations may be shadowed in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity.
所以您遇到这样一种情况,名称“只能”使用简单名称 (6.4) 来引用,但它被隐藏了,因此您不能使用简单名称 (6.4.1) 来引用它。结论是你被卡住了。
关于java - 在本地类中,如何引用封闭方法的阴影变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20804225/