在任何事件方法中(即在事件上调用的方法) 除了创建一个保留旧信息的类静态变量之外,如何以其他方式保留上一次调用的信息?
示例:
Class X {
static boolean ex = false;
static int calledTimes;
void OnClickEvent() {
if(calledTimes<=5)
{
calledTimes++;
ex = true;
}
else
ex = false;
}
}
除了这个静态标志之外,还有什么方法可以保留其他信息吗? 就我而言,我为每次调用保留了很多信息,并且我不需要太多的类变量。
有什么想法吗?
更多信息:我遇到的情况是在遍历文本文件中的每一行时调用一个方法。 我需要一个不仅仅适用于 gui 事件的通用解决方案
最佳答案
使用实例变量而不是类变量并使用实例来操作它们怎么样?这样实例就可以以实例变量的形式保存状态。
如果您想保持此类定义干净,您可以维护另一个对象作为实例变量来保留状态并使用访问器访问各个变量。
看一下这个示例实现:
public class X {
private State state;
// constructor to instantiate state
void OnClickEvent() {
if (state.getCalledTimes() <= 5) {
state.incrementCalledTimes();
state.setEx(true);
} else
state.setEx(false);
}
}
以及维护对象信息的State
类:
public class State {
private boolean ex;
private int calledTimes;
public void setEx(boolean ex) {
this.ex = ex;
}
public int getCalledTimes() {
return calledTimes;
}
public void incrementCalledTimes() {
calledTimes++;
}
}
关于Java : Can I keep information from event method through each call without using class static vars?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15189211/