java - 正在访问哪个变量,本地或类级别?

标签 java lambda scope

考虑 Lambda Expressions 中给出的以下代码:

import java.util.function.Consumer;

public class LambdaScopeTest {

    public int x = 0;

    class FirstLevel {

        public int x = 1;

        void methodInFirstLevel(int x) {

            // The following statement causes the compiler to generate
            // the error "local variables referenced from a lambda expression
            // must be final or effectively final" in statement A:
            //
            // x = 99;

            Consumer<Integer> myConsumer = (y) -> 
            {
                System.out.println("x = " + x); // Statement A
                System.out.println("y = " + y);
                System.out.println("this.x = " + this.x);
                System.out.println("LambdaScopeTest.this.x = " +
                    LambdaScopeTest.this.x);
            };

            myConsumer.accept(x);

        }
    }

    public static void main(String... args) {
        LambdaScopeTest st = new LambdaScopeTest();
        LambdaScopeTest.FirstLevel fl = st.new FirstLevel();
        fl.methodInFirstLevel(23);
    }
}

在 JavaDocs 中写道:

suppose that you add the following assignment statement immediately after the methodInFirstLevel definition statement:

 void methodInFirstLevel(int x) {
     x = 99;
     // ... }

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

System.out.println("x = " + x);

我无法理解 System.out.println("x = "+ x)(语句 A)如何访问 FirstLevel.x?不应该是methodInFirstLevel(int x)方法中传入的x吗?

最佳答案

这似乎是教程中的一个错误。我认为该段落应为:

Because of this assignment statement, the parameter x is not effectively final anymore. As a result, the Java compiler generates an error message similar to "local variables referenced from a lambda expression must be final or effectively final" where the lambda expression myConsumer tries to access the x parameter:

System.out.println("x = " + x);

我的论点基于两个观察:引用的错误消息说“局部变量”,它可能包括参数,但不包括字段。引用的 print 语句打印 23,这是参数的值,而不是 FirstLevel.x 的值。

关于java - 正在访问哪个变量,本地或类级别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40716709/

相关文章:

java - hibernate4.LocalSessionFactoryBean 无法转换为 org.hibernate.cfg.Configuration

c# - Java 中的双重检查锁定是否需要 `volatile` 而不是 C#?

java - 使用 angular2 ngFor 迭代 Map 对象

C++0x Lambda 开销

groovy:父类(super class)闭包中的变量范围(MissingPropertyException)

javascript - React/JSX 范围

java.lang.reflect.InaccessibleObjectException : Unable to make field private final transient java.net.InetSocketAddress

google-sheets - Countifs 出错,函数任何帮助表示赞赏

c# - 使用 Linq 和 Lambda 表达式从表中选择多个字段

javascript - Angular 服务内的变量范围