Presents your JAVA E-NEWSLETTER for December 9, 2002 <-------------------------------------------> IMPLEMENT A BEANCOMPARATOR WITH JAKARTA COMMONS Reflection is a powerful tool that can save time and effort. One way that it can be helpful is through the use of a BeanComparator. BeanComparators are generic comparators that can act upon any JavaBean. With a good underlying bean reflection system, they can handle a bean with bean properties, arrays, collections, and maps. If we have a java.util.List of Java Beans of type Person--where Person has an age that's an Integer, a name that's a String, and a country that's a Country bean (which itself has a String name)--then we can sort it anyway we want with a BeanComparator. Some examples: List people = ...; // list of Person objects BeanComparator comp = new BeanComparator("age"); Collections.sort(list, comp); BeanComparator comp = new BeanComparator("name"); Collections.sort(list, comp); BeanComparator comp = new BeanComparator("country.name"); Collections.sort(list, comp); There is no need to write a PersonComparator with lots of options for which property to sort by. Instead, a single BeanComparator class takes care of it all. All the magic is handled by the underlying reflection API. The following is an example of a simple BeanComparator built on top of the Jakarta Commons BeanUtils project: import java.util.Comparator; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.comparators.ComparableComparator; public class BeanComparator implements Comparator { private String attribute; private Comparator comp = new ComparableComparator(); public BeanComparator(String attrib) { this.attribute = attrib; } public int compare(Object o1, Object o2) { if(o1 == null) { return 1; } else if(o2 == null) { return -1; } try { Object ret1 = PropertyUtils.getProperty(o1, this.attribute); Object ret2 = PropertyUtils.getProperty(o2, this.attribute); return this.comp.compare(ret1, ret2); } catch(Exception e) { return 0; } } } The exception handling has been simplified, and it's assumed that the bean property to be compared implements Comparable, via the use of the ComparableComparator in the Jakarta Commons Collections project. ----------------------------------------