How to watch a variable for changes

You cannot. There is no watch-on-modification hook built into Java itself.
Obviously, you could do polling, though. But then it won’t be “live”.

AspectJ may allow such a think, but I’m not sure whether it holds for primitive variables, or only when you are using getters and setters.

The clean Java-way is to make the variable private and use getters and setters.

private valueToBeWatched;

public void setValue(int newval) {
  valueToBeWatched = newval;
  notifyWatchers();
}

public int getValue() {
  return valueToBeWatched;
}

On a side note, avoid static whenever possible. In particular public but not final.

Leave a Comment