最终和有效决赛之间的差异 [英] Difference between final and effectively final

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

问题描述

我正在玩Java 8中的lambda,我遇到警告从lambda表达式引用的局部变量必须是final或者有效的最终。我知道当我在匿名类中使用变量时,它们必须在外部类中是最终的,但仍然 - 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天全站免登陆