1 56 package org.objectstyle.cayenne.util; 57 58 import java.lang.reflect.InvocationTargetException ; 59 import java.lang.reflect.Method ; 60 import java.util.Comparator ; 61 62 import org.objectstyle.cayenne.CayenneRuntimeException; 63 64 71 public class PropertyComparator implements Comparator { 72 protected Method getter; 73 protected boolean ascending; 74 75 public static String capitalize(String s) { 76 if (s.length() == 0) { 77 return s; 78 } 79 char chars[] = s.toCharArray(); 80 chars[0] = Character.toUpperCase(chars[0]); 81 return new String (chars); 82 } 83 84 public static Method findReadMethod(String propertyName, Class beanClass) { 85 String base = capitalize(propertyName); 86 87 try { 89 return beanClass.getMethod("get" + base, null); 90 } 91 catch (Exception ex) { 92 } 94 95 try { 96 return beanClass.getMethod("is" + base, null); 97 } 98 catch (Exception ex) { 99 return null; 101 } 102 } 103 104 107 public static Object readProperty(String propertyName, Object bean) 108 throws NoSuchMethodException , IllegalAccessException , InvocationTargetException { 109 if (bean == null) { 110 throw new NullPointerException ("Null bean. Property: " + propertyName); 111 } 112 113 Method getter = findReadMethod(propertyName, bean.getClass()); 114 115 if (getter == null) { 116 throw new NoSuchMethodException ( 117 "No such property '" 118 + propertyName 119 + "' in class " 120 + bean.getClass().getName()); 121 } 122 123 return getter.invoke(bean, null); 124 } 125 126 public PropertyComparator(String propertyName, Class beanClass) { 127 this(propertyName, beanClass, true); 128 } 129 130 public PropertyComparator(String propertyName, Class beanClass, boolean ascending) { 131 getter = findReadMethod(propertyName, beanClass); 132 if (getter == null) { 133 throw new CayenneRuntimeException("No getter for " + propertyName); 134 } 135 136 this.ascending = ascending; 137 } 138 139 142 public int compare(Object o1, Object o2) { 143 return (ascending) ? compareAsc(o1, o2) : compareAsc(o2, o1); 144 } 145 146 protected int compareAsc(Object o1, Object o2) { 147 148 if ((o1 == null && o2 == null) || o1 == o2) { 149 return 0; 150 } 151 else if (o1 == null && o2 != null) { 152 return -1; 153 } 154 else if (o1 != null && o2 == null) { 155 return 1; 156 } 157 158 try { 159 Comparable p1 = (Comparable ) getter.invoke(o1, null); 160 Comparable p2 = (Comparable ) getter.invoke(o2, null); 161 162 return (p1 == null) ? -1 : p1.compareTo(p2); 163 } 164 catch (Exception ex) { 165 throw new CayenneRuntimeException("Error reading property.", ex); 166 } 167 } 168 } 169 | Popular Tags |