在从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(); } }
现在,我想在这种情况下引用s
方法的局部变量shout()
,但是教程没有说明这一点.
我已经通过谷歌和StackOverflow进行了搜索,但我无法找到正确的方法.
你不能.
JLS 6.4说:
局部变量(第14.4节),形式参数(第8.4.1节),异常参数(第14.20节)和本地类(第14.3节)只能使用简单名称(第6.2节)引用,而不是限定名称( 6.6节).
6.4.1说:
某些声明可能会在其作用域的一部分中被另一个同名声明所遮蔽,在这种情况下,简单名称不能用于引用声明的实体.
因此,您可能会使用简单名称(6.4)来引用名称"只能",但它会被遮蔽,因此您无法使用简单名称(6.4.1)引用它.结论是你被困住了.