I wrote a utility method to override equals()
using reflection. This works fine, but I wonder if this code will pass all the tests.
public static boolean checkObjectsEqualityFromInstance(Object currentObj,Object otherObj) throws Exception{
if(currentObj==null || otherObj==null){
return false;
}
else if(otherObj.getClass()!=null&¤tObj.getClass()!=null&&!currentObj.getClass().isInstance(otherObj)){
return false;
}
boolean result =true;
Field[] fields = otherObj.getClass().getDeclaredFields();
Field[] currentObjFields = currentObj.getClass().getDeclaredFields();
Map<String, Object> attriButeNameValueMap=null; /*This map to store *property name and its value of any of object in my calse the otherObj */
try {
attriButeNameValueMap=new HashMap<>();
for (Field field : fields) {
field.setAccessible(true);
Object value = field.get(otherObj);
attriButeNameValueMap.put(field.getName(), value);
}
for (Field field : currentObjFields) {
field.setAccessible(true);
Object value = field.get(currentObj);
if(attriButeNameValueMap.containsKey(field.getName())){
if(value instanceof Boolean){
result=areEqual((Boolean)value, (Boolean)attriButeNameValueMap.get(field.getName()));
}
else if(value instanceof Character){
result=result&&areEqual((Character)value, (Character)attriButeNameValueMap.get(field.getName()));
}
else if(value instanceof Long){
result=result&&areEqual((Long)value, (Long)attriButeNameValueMap.get(field.getName()));
}
else if(value instanceof Float){
result=result&&areEqual((Float)value, (Float)attriButeNameValueMap.get(field.getName()));
}
else if(value instanceof Double){
result=result&&areEqual((Double)value, (Double)attriButeNameValueMap.get(field.getName()));
}
else if(value instanceof Object[]){
result=result&& Arrays.equals((Object[])value, (Object[])attriButeNameValueMap.get(field.getName()));
}
else{
result=result&&areEqual(value, attriButeNameValueMap.get(field.getName()));
}
if(!result){
return result;
}
}
else{
return false;
}
}
} catch (IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw e;
}
return result;
}
The areEqual()
methods are overloaded for different types.
Boolean
,Character
,Double
... they can simply be treated the same as Object. – bowmore yesterday