Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep recursive objects comparison (once again)

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?

like image 298
Andremoniy Avatar asked Apr 03 '15 09:04

Andremoniy


1 Answers

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));
}
like image 198
Snekse Avatar answered Oct 20 '22 13:10

Snekse