Posted by
evanx on January 15, 2007 at 6:36 AM PST
Gooey Bean Aspect
We use CGLIB
to enhance a half-baked Java Bean with no firePropertyChange()
invocations in its setters, into a bean that does fire PropertyChangeEvent's
from its setters.
Click here to read "Gooey Bean Aspect, a tale of inner discovery"
A part of "Gooey Beans, a trilogy in 42 parts"
Code Snippet
Our QBeanInterceptor registers the PropertyDescriptor's setters methods
into a setterMap.
public class QBeanInterceptor extends QInterceptor {
BeanInfo beanInfo;
Map<Method, PropertyDescriptor> setterMap = new HashMap();
BeanPropertySupport beanAnnotation;
boolean fireByDefault;
...
public Object invoke(Object target, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
Object oldValue = null;
Object newValue = null;
PropertyDescriptor propertyDescriptor = null;
if (args.length == 1 && fireAtWill(method)) {
newValue = args[0];
propertyDescriptor = setterMap.get(method);
if (propertyDescriptor != null) {
oldValue = getOldValue(target, propertyDescriptor);
}
}
Object result = super.invoke(target, method, args, proxy);
if (propertyDescriptor != null) {
QBean bean = (QBean) target;
bean.getPropertyChangeSupport().firePropertyChange(
propertyDescriptor.getName(), oldValue, newValue);
}
return result;
}
...
}
where if the method is a key to an associated PropertyDescriptor
in setterMap, then we invoke firePropertyChange()
to fire a PropertyChangeEvent.
Demo
Here is a trivial demo that is hardly worth downloading. And it's quite large,
because it depends on a CGLIB jar.
(BeanAspectDemo, 250k/850k, unsandboxed, Java6)