How to create change listener for variable?

Sinigami picture Sinigami · Mar 15, 2013 · Viewed 84.7k times · Source

Let's say I have some variable defined using the statementint someVariable;. While the code runs, the variable's value changes.

How can I track the changes in this variable? How could I implement some Listener that behaves like onSomeVariableChangedListener?

I also need to know when some other method in one page has been executed so I can set a Listener in another class.

Answer

Kevin Condon picture Kevin Condon · Mar 15, 2013

Java gives you a simple Observer pattern implementation for this kind of thing, but you'll need to set your observed variable within a method that manages listener notifications. If you can't extend Observable, you can either use composition (i.e., have an Observable instance in your class to manage notifications), or you can take a look at java.util.Observable to get an idea of how to roll your own version.

Flux.java

import java.util.Observable;

public class Flux extends Observable {
  private int someVariable = 0;

  public void setSomeVariable(int someVariable) {
    synchronized (this) {
      this.someVariable = someVariable;
    }
    setChanged();
    notifyObservers();
  }

  public synchronized int getSomeVariable() {
    return someVariable;
  }
}

Heraclitus.java

import java.util.Observable;
import java.util.Observer;

public class Heraclitus implements Observer {
  public void observe(Observable o) {
    o.addObserver(this);
  }

  @Override
  public void update(Observable o, Object arg) {
    int someVariable = ((Flux) o).getSomeVariable();
    System.out.println("All is flux!  Some variable is now " + someVariable);
  }
}