1 17 package com.sun.syndication.feed.impl; 18 19 import java.beans.PropertyDescriptor ; 20 import java.lang.reflect.Array ; 21 import java.lang.reflect.Method ; 22 import java.io.Serializable ; 23 24 35 public class EqualsBean implements Serializable { 36 37 private static final Object [] NO_PARAMS = new Object [0]; 38 39 private Class _beanClass; 40 private Object _obj; 41 42 50 protected EqualsBean(Class beanClass) { 51 _beanClass = beanClass; 52 _obj = this; 53 } 54 55 83 public EqualsBean(Class beanClass,Object obj) { 84 if (!beanClass.isInstance(obj)) { 85 throw new IllegalArgumentException (obj.getClass()+" is not instance of "+beanClass); 86 } 87 _beanClass = beanClass; 88 _obj = obj; 89 } 90 91 102 public boolean equals(Object obj) { 103 return beanEquals(obj); 104 } 105 106 117 public boolean beanEquals(Object obj) { 118 Object bean1 = _obj; 119 Object bean2 = obj; 120 boolean eq; 121 if (bean1==null && bean2==null) { 122 eq = true; 123 } 124 else 125 if (bean1==null || bean2==null) { 126 eq = false; 127 } 128 else { 129 if (!_beanClass.isInstance(bean2)) { 130 eq = false; 131 } 132 else { 133 eq = true; 134 try { 135 PropertyDescriptor [] pds = BeanIntrospector.getPropertyDescriptors(_beanClass); 136 if (pds!=null) { 137 for (int i = 0; eq && i<pds.length; i++) { 138 Method pReadMethod = pds[i].getReadMethod(); 139 if (pReadMethod!=null && pReadMethod.getDeclaringClass()!=Object .class && pReadMethod.getParameterTypes().length==0) { Object value1 = pReadMethod.invoke(bean1, NO_PARAMS); 143 Object value2 = pReadMethod.invoke(bean2, NO_PARAMS); 144 eq = doEquals(value1, value2); 145 } 146 } 147 } 148 } 149 catch (Exception ex) { 150 throw new RuntimeException ("Could not execute equals()", ex); 151 } 152 } 153 } 154 return eq; 155 } 156 157 171 public int hashCode() { 172 return beanHashCode(); 173 } 174 175 188 public int beanHashCode() { 189 return _obj.toString().hashCode(); 190 } 191 192 193 private boolean doEquals(Object obj1, Object obj2) { 194 boolean eq = obj1==obj2; 195 if (!eq && obj1!=null && obj2!=null) { 196 Class classObj1 = obj1.getClass(); 197 Class classObj2 = obj2.getClass(); 198 if (classObj1.isArray() && classObj2.isArray()) { 199 eq = equalsArray(obj1, obj2); 200 } 201 else { 202 eq = obj1.equals(obj2); 203 } 204 } 205 return eq; 206 } 207 208 private boolean equalsArray(Object array1, Object array2) { 209 boolean eq; 210 int length1 = Array.getLength(array1); 211 int length2 = Array.getLength(array2); 212 if (length1==length2) { 213 eq = true; 214 for (int i = 0; eq && i<length1; i++) { 215 Object e1 = Array.get(array1, i); 216 Object e2 = Array.get(array2, i); 217 eq = doEquals(e1, e2); 218 } 219 } 220 else { 221 eq = false; 222 } 223 return eq; 224 } 225 226 } 227 228 | Popular Tags |