我需要从嵌套的上层类中更改一个变量(我猜可以这样调用,我是java新手,我搜索过没有找到)
代码:
public class mainClass {
public static void main(String[] args) {
boolean variableToChange = false;
Timer myTimer = new Timer();
TimerTask myTimerTask= new TimerTask() {
public void run() {
if(variableToChange==false) { //it can read the variable
variableToChange = true; //but it can't change it?!
//it triggers and error here
}
}
};
myTimer.scheduleAtFixedRate(myTimerTask, 0, 100);
}
}
最佳答案
您可以访问,但不能更改 variableToChange
,因为它在匿名内部类中并在其外部声明。
来自 JLS 8.1.3 :
Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.
在匿名内部类外部声明的变量在其中被视为 final
。
您可能正在使用 Java 8,其中 final
可以是隐式的。
“脏”解决方法(由于同步问题不推荐,但有效)是声明:
final boolean[] variableToChange = new boolean[1];
然后你就可以在里面改变它了:
variableToChange[0] = true;
关于java - 在Java中修改上层的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35378613/