无法分配最终的局部变量,因为它是在封闭类型中定义的 [英] The final local variable cannot be assigned, since it is defined in an enclosing type
问题描述
ratingS = new JSlider(1, 5, 3);
ratingS.setMajorTickSpacing(1);
ratingS.setPaintLabels(true);
int vote;
class SliderMoved implements ChangeListener {
public void stateChanged(ChangeEvent e) {
vote = ratingS.getValue();
}
}
ratingS.addChangeListener(new SliderMoved());
如果我写上面的代码,Eclipse告诉我:
If i write the above code Eclipse tells me this:
不能引用以不同方法定义的内部类
内的非最终变量投票
Cannot refer to a non-final variable vote inside an inner class defined in a different method
但如果我在 int vote 之前添加最终,则会出现此错误:
But if i add final before int vote it gives me this error:
无法分配最终的局部变量投票,因为它是在封闭类型中定义的
The final local variable vote cannot be assigned, since it is defined in an enclosing type
那么,如何解决?
推荐答案
嗯,标准技巧是使用长度为1的int数组。使var final并写入 var [0]
。确保不创建数据竞争非常重要。以您的代码为例:
Well, the standard trick is to use an int array of length one. Make the var final and write to var[0]
. It is very important to make sure you don't create a data race. Using your code as an example:
final int[] vote = {0};
class SliderMoved implements ChangeListener {
public void stateChanged(ChangeEvent e) {
vote[0] = ratingS.getValue();
}
}
由于所有这些都将在EDT上发生,包括回调调用,你应该是安全的。您还应该考虑使用匿名类:
Since all this will be happenenig on the EDT, including the callback invocation, you should be safe. You should also consider using the anonymous class:
ratingS.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) { vote[0] = ratingS.getValue(); }
});
这篇关于无法分配最终的局部变量,因为它是在封闭类型中定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!