mercredi 28 janvier 2015

Safety of Generalized Override of Object.equals() Method With Reflection

I'm tired of having to override Object.equals for all of my classes, so I came up with this overriding method that, if used in all classes in a project, appears would produce desired results.



@Override
public boolean equals(Object anObject){
if (this == anObject) {
return true;
}
//same class?
if (anObject.getClass() == this.getClass()) {
Field[] fields = this.getClass().getFields();
boolean fieldsEqual = true;
for (Field field : fields) {
try {
fieldsEqual &=
field.get(anObject).equals(field.get(this));
} catch (IllegalAccessException e) { }
}
//if fields equal, objects are equal.
return fieldsEqual;
}
//not the same class, so the objects aren't equal
return false;
}


Is this safe? The unhandled IllegalAccessException worries me a little, but given that the method first checks if this and anObject are the same class, I don't think that this would ever happen unless a field was dynamically removed or added from the class during runtime. It looks like this could be a really handy snippet of code if it's safe save for that one exception.


What do the pros here at StackOverflow think?






Aucun commentaire:

Enregistrer un commentaire