1 16 17 package org.apache.commons.beanutils; 18 19 import java.io.Serializable ; 20 import java.util.Comparator ; 21 import org.apache.commons.beanutils.PropertyUtils; 22 import org.apache.commons.collections.comparators.ComparableComparator; 23 24 42 public class BeanComparator implements Comparator , Serializable { 43 44 private String property; 45 private Comparator comparator; 46 47 57 public BeanComparator() { 58 this( null ); 59 } 60 61 79 public BeanComparator( String property ) { 80 this( property, ComparableComparator.getInstance() ); 81 } 82 83 99 public BeanComparator( String property, Comparator comparator ) { 100 setProperty( property ); 101 this.comparator = comparator; 102 } 103 104 110 public void setProperty( String property ) { 111 this.property = property; 112 } 113 114 115 121 public String getProperty() { 122 return property; 123 } 124 125 126 129 public Comparator getComparator() { 130 return comparator; 131 } 132 133 134 142 public int compare( Object o1, Object o2 ) { 143 144 if ( property == null ) { 145 return comparator.compare( o1, o2 ); 147 } 148 149 try { 150 Object value1 = PropertyUtils.getProperty( o1, property ); 151 Object value2 = PropertyUtils.getProperty( o2, property ); 152 return comparator.compare( value1, value2 ); 153 } 154 catch ( Exception e ) { 155 throw new ClassCastException ( e.toString() ); 156 } 157 } 158 159 164 public boolean equals(Object o) { 165 if (this == o) return true; 166 if (!(o instanceof BeanComparator)) return false; 167 168 final BeanComparator beanComparator = (BeanComparator) o; 169 170 if (!comparator.equals(beanComparator.comparator)) return false; 171 if (property != null) 172 { 173 if (!property.equals(beanComparator.property)) return false; 174 } 175 else 176 { 177 return (beanComparator.property == null); 178 } 179 180 return true; 181 } 182 183 186 public int hashCode() { 187 int result; 188 result = comparator.hashCode(); 189 return result; 190 } 191 } 192 | Popular Tags |