如果我有一个像这样的简单班级:
public class Example{
int y = 2;
String z = "textExample";
}
为什么在侦听器中我可以更改该类变量的成员,但现在可以更改变量本身?或就此而言,甚至是诸如int
之类的原语。
想象一下这个函数在另一个类中:
public class newClass {
protected void doActivate() {
ItemCreation model = new Itemcreation(); //A class with visible moving parts
Example ex = new Example();
int i = 2;
model.getSourceProperty().addListener((o, oldVal, newVal) -> {
//do stuff
ex.z = "sss"; //THIS I CAN DO and Works
Example exTmp = new Example();
ex = exTmp; //This complains with message: Local variable ex defined in an enclosing scope must be final or effectively final
i= 4;//This also complains with message: Local variable i defined in an enclosing scope must be final or effectively final
});
}
我在网上看了很多,却没有找到任何答案。我发现的全部内容是:“ Java语言具有一种功能,其中从(匿名)内部类访问的局部变量必须(有效)是最终的” 。但是如果是这样,为什么我不能更改不是最终版本的Example
类的成员?
答案 0 :(得分:0)
为此,您需要一个最终标记的对象包装器。
签出提供所需功能的原子软件包: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html
体验:
protected void doActivate() {
ItemCreation model = new Itemcreation(); //A class with visible moving parts
final AtomicReference<Example> ex = new AtomicReference<>(new Example());
final AtomicInteger i = new AtomicInteger(2);
model.getSourceProperty().addListener((o, oldVal, newVal) -> {
ex.get().z = "sss";
Example exTmp = new Example();
ex.set(exTmp);
i.set(4);
});
}