【问题标题】:Surprising access to fields with Java anonymous class使用 Java 匿名类对字段的惊人访问
【发布时间】:2016-09-08 00:43:20
【问题描述】:

我试图更好地理解 Java 中匿名类的概念。从本网站的其他答案中,我了解到匿名类可以使用 OuterClass.this.myField 访问封闭类的非最终字段。

我用一个接口AnonInt 和一个类AnonTest 和一个方法foo 创建了以下简单的测试用例,该方法返回一个实现AnonInt 的匿名类的实例。尽管我使用的是System.out.println(a) 而不是System.out.println(AnonTest.this.a),但代码可以工作并打印正确的结果。这怎么可能?

public interface AnonInt {
    void print();
}

public class AnonTest {

    private int a;

    public AnonTest(int a) {
        this.a = a;
    }

    public AnonInt foo() {
        return new AnonInt() {

            public void print() {
                System.out.println(a);
            }
        };
    }

    public static void main(String[] args) {
        AnonTest at = new AnonTest(37);
        AnonInt ai = at.foo();
        ai.print();
    }
}

【问题讨论】:

    标签: java anonymous-class


    【解决方案1】:

    尽管我使用的是System.out.println(a) 而不是System.out.println(AnonTest.this.a),但代码可以正常工作并打印正确的结果。这怎么可能?

    由于在您的上下文中对 a 的引用是明确的,因此这两个表达式引用了相同的字段。

    通常,AnonTest.this 在非常特定的上下文中是必需的 - 当您的方法需要访问 AnonTest 对象本身,而不是访问其成员之一时。对于您的程序,这是不必要的:编译器将表达式a 解析为对象AnonTest.this.a,并将其传递给System.out.println。

    【讨论】:

    • 谢谢!您能否评论 Rich O'Kelly 在此线程中的回答:stackoverflow.com/questions/9545076/…?你需要'OuterClass.this.dialog'来访问'dialog'吗?谢谢!
    • @AlexandreVandermonde 由于旧问题对于定义 dialog 字段的类中的其他内容有些不清楚,因此答案尽量保守,并涵盖两者之间命名冲突的可能性dialog 中的 OuterClass.this 和其他一些可能在范围内的 dialog 字段或变量。当情况明确时,他可以废弃他的dlg 变量,并使用dialog 代替它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    相关资源
    最近更新 更多