我正在尝试从其他类获取变量的更新值。变量的值正在更新,但仅限于它自己的类。虽然另一个类试图通过引用访问这些值,但仍然获取旧值。假设class1
中有一个不断更新的private boolean
变量。
而class2
通过getter方法
访问class1
的boolean
变量,如下所示:
CLASS 1 CODE:
class A {
private boolean state;
boolean getState() {
return state;
}
}
这里变量state
的值通过ActionEvent
持续更新
CLASS 2 CODE:
class B {
void go() {
A a = new A();
while(true) {
if(a.getState()) {
//CODE
}
}
}
}
在这里,我总是在 B 类
中获取 state
变量的原始值,尽管该值在 A 类
中更新。那么,如何从另一个类引用中获取变量的更新值?
EDIT: It's kinda strange but the variables updates when the method is somehow called or refreshed. Like this:
CLASS 2 CODE:
class B {
void go() {
A a = new A();
while(true) {
System.out.println(a.getState());
if(a.getState()) {
//CODE
}
}
}
}
添加System.out.println(a.getState());
后,我们就得到了更新后的值。请解释一下!
最佳答案
您在每次循环迭代时创建 A 的新实例。 只需移动 A a = new A();一队:
class B {
void go() {
A a = new A();
while(true) {
if(a.getState()) {
//CODE
}
}
}
}
关于java - 如何获取java变量的更新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37366485/