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; } } } |