Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker 诊断工具


为什么匿名内部类引用外部局部变量不用加 final 也不报错

Java 面试 评论 1 大约 759 字

Java 代码

匿名内部类引用了局部变量,编写代码时没有用final修饰也没有报错,因为编译器会检查后续有没有写操作,如果有,则在编译器时就会报错(包括匿名内部类方法体内也不能进行写操作)。如果只有读操作,编译器会帮忙加上final关键字。

public class Test {

    public static void main(String[] args) {
        int x = 10;
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // x = 30;
                System.out.println(x);
            }
        };
        // x = 20;
        System.out.println(x);
    }

}

反编译 class

可以看到:反编译后编译器帮忙加了final关键字。

public class Test {
    public Test() {
    }

    public static void main(String[] args) {
        final int x = 10;
        Runnable var10000 = new Runnable() {
            public void run() {
                System.out.println(x);
            }
        };
    }
}
阅读 1013 · 发布于 2022-05-16

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
  • fHLvlxbf 1楼
    e
    Chrome | Windows 10 2023-07-24
随便看看 换一批