为什么java 8 lambdas允许访问非final类变量? [英] Why do java 8 lambdas allow access to non-final class variables?

查看:169
本文介绍了为什么java 8 lambdas允许访问非final类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解为什么编译器不接受以下内容:

I understand why the following is not accepted by the compiler:

class Foo {
    public Supplier<String> makeSupplier() {
        String str = "hello";
        Supplier<String> supp = () -> return str;

        // gives the expected compile error because
        // str is not effectively final
        // (str is a local variable, compile-time error
        //  as per JLS 15.27.2.)
        str = "world";

        return supp;
    }
}

让我感到困惑的是,编译器接受以下内容,并且单元测试通过:

What puzzles me is that the compiler accepts the following, and that the unit test passes:

class Bar {
    private String str = "hello";

    public void setStr(String str) {
        this.str = str;
    }

    public Supplier<String> makeSupplier() {
        Supplier<String> supp = () -> { return str; };
        return supp;
    }

    @Test 
    public void Unit_lambdaCapture() {    
        Supplier<String> supp = makeSupplier();
        Assert.assertEquals(supp.get(), "hello");
        setStr("foo");
        Assert.assertEquals(supp.get(), "foo");
    }
}

为什么上述有效且正常工作?欢迎使用JLS相关部分的指针(第15.27.2节,仅讨论局部变量)。

Why is the above valid and working correctly? Pointers to relevant sections of the JLS are welcome (section 15.27.2. only talks about local variables).

推荐答案

我们都同意第一个例子不起作用,因为局部变量或参数必须最终或有效最终将在 lambda表达体

We all agree that the first example won't work as local variables or parameters must be final or effectively final to be used within a lambda expression body.

但是你的第二个例子不涉及局部变量或参数,因为 str 是一个实例字段。 Lambda表达式可以像实例方法一样访问实例字段:

But your second example does not involve local variables or parameters, as str is an instance field. Lambda expressions can accessing instance fields the same way as instance methods:

15.27.2。 Lambda Body


lambda主体是单个表达式或块(第14.2节)。像方法体一样,lambda体描述了每次调用时都会执行的代码。

A lambda body is either a single expression or a block (§14.2). Like a method body, a lambda body describes code that will be executed whenever an invocation occurs.

实际上,java编译器会创建一个私有方法 lambda $ 0 超出lambda表达式,只需访问实例字段 str

In fact, the java compiler creates a private method lambda$0 out of your lambda expression, that simply accesses the instance field str:

private java.lang.String lambda$0() {
    0 aload_0;                /* this */
    1 getfield 14;            /* .str */
    4 areturn;
}

另一种观点:您也可以实施供应商使用普通的匿名内部类:

Another point of view: You could also implement the Supplier using a plain-old anonymous inner class:

public Supplier<String> makeSupplier() {
    return new Supplier<String>() {
        public String get() { return str; }
    };
}

从内部类访问实例字段非常常见,而不是Java 8的专业。

Accessing instance fields from inner classes is very common and not a speciality of Java 8.

这篇关于为什么java 8 lambdas允许访问非final类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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