【发布时间】:2020-02-27 23:11:59
【问题描述】:
我想知道 lambdas 外部引用是如何工作的。让我解释一下:
假设我有这个供应商实现和这个模型类:
public class TestSupplierImpl implements Supplier<Boolean> {
public Predicate<Integer> predicate;
public TestSupplierModel model;
public TestSupplierImpl() {
this.predicate = i -> model.something.equals(i);
}
@Override
public Boolean get() {
return predicate.test(3);
}
}
class TestSupplierModel {
public Integer something;
public TestSupplierModel(Integer something) {
this.something = something;
}
}
然后我执行以下代码:
TestSupplierImpl test = new TestSupplierImpl(); // line 1
test.model = new TestSupplierModel(3); // line 2
Boolean resultado = test.get(); // line 3
第 1 行:创建 TestSupplierImpl 的新实例。这个新实例的谓词具有 model 的空引用。这是有道理的,因为在创建谓词时,模型引用为空。 第 2 行:为变量 model 分配一个新的 TestSupplierModel 实例。 第 3 行:test.predicate 现在具有带有新分配值的 model 引用。 这是为什么呢?
我不明白为什么,当我更改 model 引用时,谓词会将其模型引用更新为新的。怎么样?
提前致谢!
【问题讨论】:
-
因为 lambda 捕获了
this(即TestSupplierImpl的实例),而model实际上是指TestSupplierImpl.this.model。