Java Detect Variable Change Using PropertyChangeSupport and PropertyChangeListener

Posted by Sam on Stack Overflow See other posts from Stack Overflow or by Sam
Published on 2011-01-03T21:50:16Z Indexed on 2011/01/03 21:53 UTC
Read the original article Hit count: 182

Filed under:
|

I'm trying to print out debug statements when some third party code changes a variable. For example, consider the following:

public final class MysteryClass {

private int secretCounter;

public synchronized int getCounter() {
    return secretCounter;
}

public synchronized void incrementCounter() {
    secretCounter++;
}

}

public class MyClass {

public static void main(String[] args) {
    MysteryClass mysteryClass = new MysteryClass();
    // add code here to detect calls to incrementCounter and print a debug message
}

I don't have the ability to change the 3rd party MysteryClass, so I thought that I could use PropertyChangeSupport and PropertyChangeListener to detect changes to the secretCounter:

public class MyClass implements PropertyChangeListener {

    private PropertyChangeSupport propertySupport = new PropertyChangeSupport(this);

    public MyClass() {
        propertySupport.addPropertyChangeListener(this);
    }

    public void propertyChange(PropertyChangeEvent evt) {
        System.out.println("property changing: " + evt.getPropertyName());
    }

    public static void main(String[] args) {
        MysteryClass mysteryClass = new MysteryClass();
        // do logic which involves increment and getting the value of MysteryClass
    }
}

Unfortunately, this did not work and I have no debug messages printed out. Does anyone see what is wrong with my implementation of the PropertyChangeSupport and Listener interfaces? I want to print a debug statement whenever incrementCounter is called or the value of secretCounter changes.

© Stack Overflow or respective owner

Related posts about java

Related posts about propertychangesupport