There are two similar questions on SO:
Is there a Java reflection utility for deep comparison of two objects?
Deep reflective comparison equals
but, itβs funny, not one of them gives a completely correct answer to the question.
What I and other authors really like is some kind of method in some library that just says that two objects are equal or not:
boolean deepEquals(Object obj1, Object obj2)
i.e. without any exceptions etc.
apache EqualsBuilder is wrong because it is not much compared.
Unitils also a bad solution because its method does not return true or false ; it just throws an exception if the comparison was unsuccessful. Of course, it could be used as follows:
Difference difference = ReflectionComparatorFactory.createRefectionComparator(new ReflectionComparatorMode[]{ReflectionComparatorMode.LENIENT_ORDER, ReflectionComparatorMode.IGNORE_DEFAULTS}).getDifference(oldObject, newObject);
but it seems very ugly, and the Unitils library completely seems too complex for the required comparison purposes.
In addition, it is completely clear how to create such deepEquals for yourself, but it is unlikely that there are no common libraries used that contain an already implemented method like this. Any ideas?
java reflection compare
Andremoniy
source share