简体   繁体   English

获取有关静态变量(类变量)的PropertyChangeListener通知

[英]Get PropertyChangeListener notification on static variables (class variables)

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. 我知道在Java中我可以将自己注册为实例变量的侦听器,但不能使用静态(类)变量来实现。 Can anyone have workaround for this problem? 任何人都可以解决此问题吗? Thanks 谢谢

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: 如果您使用静态的setter方法来更改它,并将变量设为私有,则很容易:

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. 当然,在多个线程想要设置值的情况下,您可能希望setBar是一个同步方法,您可能希望在其他人可以再次更改值之前通知所有侦听器,但这取决于您的要求。

您始终可以使用静态访问器包装静态变量,并在这些访问器中添加代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM