最终和有效最终之间的区别 [英] Difference between final and effectively final

查看:24
本文介绍了最终和有效最终之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Java 8 中使用 lambdas 并遇到警告从 lambda 表达式引用的局部变量必须是最终的或有效的最终.我知道当我在匿名类中使用变量时,它们在外部类中必须是 final,但是 - finaleffectively final 之间有什么区别?

I'm playing with lambdas in Java 8 and I came across warning local variables referenced from a lambda expression must be final or effectively final. I know that when I use variables inside anonymous class they must be final in outer class, but still - what is the difference between final and effectively final?

推荐答案

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

例如,假设变量 numberLength 未声明为 final,并且您在 PhoneNumber 构造函数中添加了标记的赋值语句:

For example, suppose that the variable numberLength is not declared final, and you add the marked assignment statement in the PhoneNumber constructor:

public class OutterClass {  

  int numberLength; // <== not *final*

  class PhoneNumber {

    PhoneNumber(String phoneNumber) {
        numberLength = 7;   // <== assignment to numberLength
        String currentNumber = phoneNumber.replaceAll(
            regularExpression, "");
        if (currentNumber.length() == numberLength)
            formattedPhoneNumber = currentNumber;
        else
            formattedPhoneNumber = null;
     }

  ...

  }

...

}

由于这个赋值语句,变量 numberLength 不再有效.因此,Java 编译器会生成类似于从内部类引用的局部变量必须是最终的或有效的最终变量"的错误消息,其中内部类 PhoneNumber 尝试访问 numberLength 变量:

Because of this assignment statement, the variable numberLength is not effectively final anymore. As a result, the Java compiler generates an error message similar to "local variables referenced from an inner class must be final or effectively final" where the inner class PhoneNumber tries to access the numberLength variable:

http://codeinventions.blogspot.in/2014/07/difference-between-final-and.html

http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html

这篇关于最终和有效最终之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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