Domanda

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

È stato utile?

Soluzione

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

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top