Just Code‎ > ‎

Java - Generic Entity Comparer to check Equality of all fields

posted Jun 18, 2013, 3:04 AM by Peter Henell   [ updated Jun 18, 2013, 3:05 AM ]
Will check equality of all fields of any entity. 

Note: Only values from getters will be compared


import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class EqualComparer {
    public static boolean isEqual(final Object a, final Object b) {
        if (!isTypeEqual(a, b)) {
            return false;
        }

        Object valueA;
        Object valueB;

        try {
            // Get all getters of the objects
            PropertyDescriptor[] descriptors = Introspector.getBeanInfo(a.getClass(), Object.class).getPropertyDescriptors();
            if (descriptors.length == 0) {
                // no getters, compare them as they are.
                if (!compare(a, b)) {
                    return false;
                }
            } else {
                for (PropertyDescriptor propertyDescriptor : descriptors) {

                    Method m = propertyDescriptor.getReadMethod();
                    valueA = m.invoke(a, (Object[]) null);
                    valueB = m.invoke(b, (Object[]) null);

                    if (!compare(valueA, valueB)) {
                        System.out.println(m.getName() + ": [" + valueA + "] = [" + valueB + "]");
                        return false;
                    }

                }
            }
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | IntrospectionException e) {
            e.printStackTrace();
            return false;

        }

        return true;
    }


    private static boolean areBothNull(final Object a, final Object b) {
        return (a == null && b == null);
    }


    private static boolean isTypeEqual(final Object a, final Object b) {
        if (areBothNull(a, b)) {
            return false;
        }

        return a.getClass().equals(b.getClass());
    }


    private static boolean compare(final Object a, final Object b) {
        if (a == null) {
            return false;
        } else if (b == null) {
            return false;
        }
        return a.equals(b);
    }
}
Comments