Java停止了内部类中非final变量的错误(java 8) [英] Java stopped erroring on non-final variables in inner classes (java 8)

查看:69
本文介绍了Java停止了内部类中非final变量的错误(java 8)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 7在下面的代码中说不能引用封闭范围中定义的非最终局部变量消息:

Java 7 was saying "Cannot refer to the non-final local variable message defined in an enclosing scope" on following code:

public class Runner {   
    public static void main(String[] args) {

        String message = "Hello world";

        new Runnable() {
            @Override
            public void run() {
                System.out.println(message);
            }
        }.run();
    }
}

Java 8没有。

怀疑这是关于向Java添加函数式编程功能。

Suspect this is about adding functional programming features to Java.

它是否同样处理代码?

推荐答案

Java 8隐式生成消息 final,因为它永远不会被修改。尝试在代码中的任何位置修改它,您将收到编译错误(因为这会删除隐式 final )。

Java 8 implicitly makes message final because it is never modified. Try modifying it anywhere in your code and you will get a compilation error (because this removes the implicit final).

这被称为有效的最终。引用来自文档


但是,从Java SE 8开始,本地类可以访问最终的封闭块的局部变量和参数或有效决赛。初始化后永远不会更改其值的变量或参数实际上是最终的。

However, starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final.

这篇关于Java停止了内部类中非final变量的错误(java 8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆