java - 在本地类中,如何引用封闭方法的阴影变量?

标签 java class

我在学习的时候就在想这个情况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/

相关文章:

java - “找不到或加载主类”是什么意思?

android - android 3.0+ 中的 ACTION_MEDIA_BUTTON 静态广播接收器

java - 如何从android中的语音合成器保存音频文件(android.speech.tts)?

java - 如何在android中的触摸比例动画上应用imageView?

java - 我可以在 JVM 在 OOM 上调用的脚本中使用 "kill %p"

c# - 你如何解决类型和对象之间常见的命名冲突?

python - 对象没有属性-python类执行

java - Xstream 在解码时不维护子元素的顺序

java - 如何在jsp include标签的页面属性中使用变量?

c++函数中的新实例