1 4 package org.oddjob.monitor.control; 5 6 import java.beans.PropertyChangeListener ; 7 import java.lang.reflect.InvocationTargetException ; 8 import java.lang.reflect.Method ; 9 import java.util.HashMap ; 10 import java.util.Map ; 11 12 import org.apache.log4j.Logger; 13 14 17 public class PropertyChangeHelper { 18 19 private static final Logger logger = Logger 20 .getLogger(PropertyChangeHelper.class); 21 22 static final Map helpers = new HashMap (); 23 24 25 private Method addPropListenerMethod; 26 27 28 private Method removePropListenerMethod; 29 30 private PropertyChangeHelper(Class bean) { 31 Class beanClass = bean.getClass(); 32 Class [] argClasses = { PropertyChangeListener .class }; 33 try { 34 addPropListenerMethod = beanClass.getMethod( 35 "addPropertyChangeListener", argClasses); 36 37 removePropListenerMethod = beanClass.getMethod( 38 "removePropertyChangeListener", argClasses); 39 } catch (SecurityException e) { 40 logger.debug(e); 41 } catch (NoSuchMethodException e) { 42 } 44 45 } 46 47 private static PropertyChangeHelper lookup(Class bean) { 48 synchronized (helpers) { 49 PropertyChangeHelper helper = (PropertyChangeHelper) helpers 50 .get(bean); 51 if (helper == null) { 52 helper = new PropertyChangeHelper(bean); 53 helpers.put(bean, helper); 54 } 55 return helper; 56 } 57 } 58 59 public static void addPropertyChangeListener(Object obj, 60 PropertyChangeListener l) { 61 PropertyChangeHelper helper = lookup(obj.getClass()); 62 if (helper.addPropListenerMethod == null) { 63 return; 64 } 65 Object [] args = { obj }; 66 try { 67 helper.addPropListenerMethod.invoke(obj, args); 68 } catch (IllegalArgumentException e) { 69 logger.debug(e); 70 } catch (IllegalAccessException e) { 71 logger.debug(e); 72 } catch (InvocationTargetException e) { 73 logger.debug(e); 74 } 75 } 76 77 public static void removePropertyChangeListener(Object obj, 78 PropertyChangeListener l) { 79 PropertyChangeHelper helper = lookup(obj.getClass()); 80 if (helper.removePropListenerMethod == null) { 81 return; 82 } 83 Object [] args = { obj }; 84 try { 85 helper.removePropListenerMethod.invoke(obj, args); 86 } catch (IllegalArgumentException e) { 87 logger.debug(e); 88 } catch (IllegalAccessException e) { 89 logger.debug(e); 90 } catch (InvocationTargetException e) { 91 logger.debug(e); 92 } 93 } 94 } 95 | Popular Tags |