1 package org.infoglue.cms.util.sorters; 2 3 import java.util.Comparator ; 4 5 import org.apache.commons.beanutils.PropertyUtils; 6 import org.apache.log4j.Logger; 7 8 13 public class ReflectionComparator implements Comparator 14 { 15 private final static Logger logger = Logger.getLogger(ReflectionComparator.class.getName()); 16 17 private String sortProperty; 18 19 public ReflectionComparator(String prop) 20 { 21 sortProperty = prop; 22 } 23 24 public int compare(Object o1, Object o2) 25 { 26 Comparable valueOne = getProperty(o1, sortProperty); 27 Comparable valueTwo = getProperty(o2, sortProperty); 28 return valueOne.compareTo(valueTwo); 29 } 30 31 private Comparable getProperty(Object o, String property) 32 { 33 try 34 { 35 Object propertyObject = PropertyUtils.getProperty(o, sortProperty); 36 if(propertyObject instanceof String ) 37 return (Comparable )propertyObject.toString().toLowerCase(); 38 else 39 return (Comparable )propertyObject; 40 } 41 catch (Exception e) 42 { 43 logger.info(getClass().getName() + " Error finding property " + property, e); 44 return new Comparable () 45 { 46 public int compareTo(Object o) 47 { 48 return 0; 49 } 50 }; 51 } 52 } 53 } 54 | Popular Tags |