Question

In my code I need to know when a specific static variables change is value. I know that in Java I can register myself as listener for the instance variables but I can' t do that with the static (class) variables. Can anyone have workaround for this problem? Thanks

Was it helpful?

Solution

You can always wrap your static variable with static accessors and add code in those accessors.

OTHER TIPS

It depends on how you access the static variable. If you use a static setter method to change it, and keep the variable private, it's easy:

public class Foo {
   private static int bar = 0;

   private static PropertyChangeSupport propertyChangeSupport =
       new PropertyChangeSupport(Foo.class);

   public static void addPropertyChangeListener(PropertyChangeListener listener) {
       propertyChangeSupport.addPropertyChangeListener(listener);
   }

   public static void setBar(int bar) {
       int oldVal = Foo.bar;
       Foo.bar = bar;
       propertyChangeSupport.firePropertyChange("bar", oldVal, Foo.bar);
   }
}

Of course, it's likely you'll want setBar to be a synchronized method in case multiple threads want to set the value, you probably want all the listeners notified before someone else can change the value again, but that depends on your requirements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top