KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > infoglue > cms > util > sorters > ReflectionComparator


1 package org.infoglue.cms.util.sorters;
2
3 import java.util.Comparator JavaDoc;
4
5 import org.apache.commons.beanutils.PropertyUtils;
6 import org.apache.log4j.Logger;
7
8 /**
9  * Sort on a particular property, using reflection to find the value
10  *
11  * @author Frank Febbraro (frank@phase2technology.com)
12  */

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