【发布时间】:2020-04-07 08:02:01
【问题描述】:
我想不出为什么捕获的变量在 lambda 表达式中是最终的或实际上是最终的。我查看了this question,确实没有得到答案。
这个变量捕获是什么?
当我为我的问题寻找解决方案时,我读到这些变量是最终的,因为并发问题。但是对于这种情况,为什么我们不能用 reentrant lock 对象锁定 lambda 中的任务代码。
public class Lambda {
private int instance=0;
public void m(int i,String s,Integer integer,Employee employee) {
ActionListener actionListener = (event) -> {
System.out.println(i);
System.out.println(s);
System.out.println(integer);
System.out.println(employee.getI());
this.instance++;
employee.setI(4);
integer++;//error
s="fghj";//error
i++;//error
};
}
}
在这个特定的代码中,我想知道最后三个语句出错的原因,以及为什么我们要改变Employee,因为它是一个局部变量。(Employee 只是一个具有@987654325 的getter 和setter 的类@.)
我也想知道为什么我们也可以改变this.instance。
感谢对我上面提到的所有事实的完整详细回答。
【问题讨论】:
-
this和employee也是最终版本。您不能重新分配它们:employee = new Employee();也将是一个错误。