1

Java does not seem to deliver an implementation of PropertyChangeSupport with weak references to registered PropertyChangeListeners.

It would not be very hard to implement this, but before I re-invent the wheel, does anyone know whether such feature has been implemented in any open source library? It does not seem so, but someone may know better on SO.

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
  • Hi, what's your use case? Why do the listener references need to be weak? This *could* indicate that your listeners aren't unregistering themselves correctly. – Paul Grime Sep 06 '11 at 09:45
  • @Paul I may need to expose such classes and won't have control on code which should unregister these listeners properly. It is a defensive approach. – Jérôme Verstrynge Sep 06 '11 at 10:16

1 Answers1

2

Would this Netbeans WeakListeners page help ?

Example:

public class Observer {
  private Listener listener;

  private void registerTo(Source source) {
      listener = new Listener();
      source.addChangeListener(WeakListeners.change (listener, source));
  }

  private class Listener implements ChangeListener {
      public void stateChanged(ChangeEvent e) {
          doSomething();
      }
  }
}
Paul Grime
  • 14,970
  • 4
  • 36
  • 58
  • Somehow yes, though this implementation does not seem very clean (Javadoc says 'The unregistration is done using reflection'). – Jérôme Verstrynge Sep 06 '11 at 15:17
  • Yeah, that seems to be as a result of its genericity I guess. It can act as a weak listener for several (any?) listener type that follows the Javabeans conventions. – Paul Grime Sep 06 '11 at 18:24