Re: Binding to a POJO
On Fri, 4 Mar 2011, Steve Sobol wrote:
The often-cited problem with either JGoodies or BeansBinding is this: it
introduces code bloat. Instead of
public void setFoo(Object newFoo) {
this.foo=newFoo;
}
you have to do this:
public void setFoo(Object newFoo) {
String oldFoo = this.foo;
this.foo=newFoo;
// support is a previously-initialized
// instance of java.beans.PropertyChangeSupport
support.firePropertyChange(propertyName, oldValue, newValue);
}
I came up with a solution that will allow you to do this instead:
public void setFoo(Object newFoo {
changeProperty("foo",this.foo,newFoo);
}
Okay, how about:
public class PropertyChangeUtils {
private static final PropertyChangeSupport support; // initialise this somehow
public static <T> T change(String propertyName, T oldValue, T newValue) {
support.firePropertyChange(propertyName, oldValue, newValue);
return newValue;
}
}
import static PropertyChangeUtils.change;
private String foo;
public void setFoo(Object foo) {
this.foo = change("foo", this.foo, foo);
}
The code in the setter is fractionally (well, ~25%) more complicated than
with your version, but there's no reflection, and you have static type
safety.
It does fire the property change event before actually changing the
property, though; i don't know enough about Swing to know if that would be
a problem.
tom
--
If you can't open it, you don't own it -- The Maker's Bill of Rights