There are two similar questions on SO:
Is there a Java utility to do a deep comparison of two objects?
Deep reflective compare equals
but, it is funny, none of them gives a fully correct answer to the question.
What I and other questions' authors really want, is some method in some library which will just tell whether the given two objects are equal or not:
boolean deepEquals(Object obj1, Object obj2)
i.e. without throwing any exception and so on.
apache
's EqualsBuilder
is not the solution, because it doesn't deep compare.
Unitils
seems also be a bad decision, because its method do not return true
or false
; it just throws an exception if comparison has failed. Of course, it could be used like this:
Difference difference = ReflectionComparatorFactory.createRefectionComparator(new ReflectionComparatorMode[]{ReflectionComparatorMode.LENIENT_ORDER, ReflectionComparatorMode.IGNORE_DEFAULTS}).getDifference(oldObject, newObject);
but it seems to be very ugly, and unitils
library entirely seems to be too heavy for the required compare purposes.
Furthermore, it is quite clear how to create such deepEquals
by myself, but it is unlikely that there aren't common used libraries which contain an already implemented method like this. Any ideas?
I don't think the Apache EqualsBuilder
is a terrible answer, but for a simple interface that does what you want, you would need to wrap the call a bit. Here's an example.
public static <T> boolean matches(T actual, T expected, String... excludedFields) {
assert actual != null;
assert expected != null;
boolean matches = EqualsBuilder.reflectionEquals(actual, expected,
false /* testTransients */,
null /* reflectUpToClass */,
true /* testRecursive */,
excludedFields);
if (!matches) {
log.warn("Actual result doesn't match.");
logComparison(actual, expected);
}
return matches;
}
public static <T> void logComparison(T actual, T expected) {
//Making sure hashcodes don't thrown an exception
assert actual.hashCode() > Integer.MIN_VALUE;
assert expected.hashCode() > Integer.MIN_VALUE;
log.warn("Expected: \n" + reflectionToString(expected));
log.warn("Actual: \n" + reflectionToString(actual));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With