    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.lang3.builder;
    018
    019import java.lang.reflect.AccessibleObject;
    020import java.lang.reflect.Field;
    021import java.lang.reflect.Modifier;
    022import java.util.ArrayList;
    023import java.util.Collection;
    024import java.util.HashSet;
    025import java.util.List;
    026import java.util.Set;
    027
    028import org.apache.commons.lang3.ArrayUtils;
    029import org.apache.commons.lang3.ClassUtils;
    030import org.apache.commons.lang3.tuple.Pair;
    031
    032/**
    033 * <p>Assists in implementing {@link Object#equals(Object)} methods.</p>
    034 *
    035 * <p> This class provides methods to build a good equals method for any
    036 * class. It follows rules laid out in
    037 * <a href="http://www.oracle.com/technetwork/java/effectivejava-136174.html">Effective Java</a>
    038 * , by Joshua Bloch. In particular the rule for comparing <code>doubles</code>,
    039 * <code>floats</code>, and arrays can be tricky. Also, making sure that
    040 * <code>equals()</code> and <code>hashCode()</code> are consistent can be
    041 * difficult.</p>
    042 *
    043 * <p>Two Objects that compare as equals must generate the same hash code,
    044 * but two Objects with the same hash code do not have to be equal.</p>
    045 *
    046 * <p>All relevant fields should be included in the calculation of equals.
    047 * Derived fields may be ignored. In particular, any field used in
    048 * generating a hash code must be used in the equals method, and vice
    049 * versa.</p>
    050 *
    051 * <p>Typical use for the code is as follows:</p>
    052 * <pre>
    053 * public boolean equals(Object obj) {
    054 *   if (obj == null) { return false; }
    055 *   if (obj == this) { return true; }
    056 *   if (obj.getClass() != getClass()) {
    057 *     return false;
    058 *   }
    059 *   MyClass rhs = (MyClass) obj;
    060 *   return new EqualsBuilder()
    061 *                 .appendSuper(super.equals(obj))
    062 *                 .append(field1, rhs.field1)
    063 *                 .append(field2, rhs.field2)
    064 *                 .append(field3, rhs.field3)
    065 *                 .isEquals();
    066 *  }
    067 * </pre>
    068 *
    069 * <p> Alternatively, there is a method that uses reflection to determine
    070 * the fields to test. Because these fields are usually private, the method,
    071 * <code>reflectionEquals</code>, uses <code>AccessibleObject.setAccessible</code> to
    072 * change the visibility of the fields. This will fail under a security
    073 * manager, unless the appropriate permissions are set up correctly. It is
    074 * also slower than testing explicitly.  Non-primitive fields are compared using
    075 * <code>equals()</code>.</p>
    076 *
    077 * <p> A typical invocation for this method would look like:</p>
    078 * <pre>
    079 * public boolean equals(Object obj) {
    080 *   return EqualsBuilder.reflectionEquals(this, obj);
    081 * }
    082 * </pre>
    083 *
    084 * <p>The {@link EqualsExclude} annotation can be used to exclude fields from being
    085 * used by the <code>reflectionEquals</code> methods.</p>
    086 *
    087 * @since 1.0
    088 */
    089public class EqualsBuilder implements Builder<Boolean> {
    090
    091    /**
    092     * <p>
    093     * A registry of objects used by reflection methods to detect cyclical object references and avoid infinite loops.
    094     * </p>
    095     *
    096     * @since 3.0
    097     */
    098    private static final ThreadLocal<Set<Pair<IDKey, IDKey>>> REGISTRY = new ThreadLocal<>();
    099
    100    /*
    101     * NOTE: we cannot store the actual objects in a HashSet, as that would use the very hashCode()
    102     * we are in the process of calculating.
    103     *
    104     * So we generate a one-to-one mapping from the original object to a new object.
    105     *
    106     * Now HashSet uses equals() to determine if two elements with the same hash code really
    107     * are equal, so we also need to ensure that the replacement objects are only equal
    108     * if the original objects are identical.
    109     *
    110     * The original implementation (2.4 and before) used the System.identityHashCode()
    111     * method - however this is not guaranteed to generate unique ids (e.g. LANG-459)
    112     *
    113     * We now use the IDKey helper class (adapted from org.apache.axis.utils.IDKey)
    114     * to disambiguate the duplicate ids.
    115     */
    116
    117    /**
    118     * <p>
    119     * Returns the registry of object pairs being traversed by the reflection
    120     * methods in the current thread.
    121     * </p>
    122     *
    123     * @return Set the registry of objects being traversed
    124     * @since 3.0
    125     */
    126    static Set<Pair<IDKey, IDKey>> getRegistry() {
    127        return REGISTRY.get();
    128    }
    129
    130    /**
    131     * <p>
    132     * Converters value pair into a register pair.
    133     * </p>
    134     *
    135     * @param lhs <code>this</code> object
    136     * @param rhs the other object
    137     *
    138     * @return the pair
    139     */
    140    static Pair<IDKey, IDKey> getRegisterPair(final Object lhs, final Object rhs) {
    141        final IDKey left = new IDKey(lhs);
    142        final IDKey right = new IDKey(rhs);
    143        return Pair.of(left, right);
    144    }
    145
    146    /**
    147     * <p>
    148     * Returns <code>true</code> if the registry contains the given object pair.
    149     * Used by the reflection methods to avoid infinite loops.
    150     * Objects might be swapped therefore a check is needed if the object pair
    151     * is registered in given or swapped order.
    152     * </p>
    153     *
    154     * @param lhs <code>this</code> object to lookup in registry
    155     * @param rhs the other object to lookup on registry
    156     * @return boolean <code>true</code> if the registry contains the given object.
    157     * @since 3.0
    158     */
    159    static boolean isRegistered(final Object lhs, final Object rhs) {
    160        final Set<Pair<IDKey, IDKey>> registry = getRegistry();
    161        final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
    162        final Pair<IDKey, IDKey> swappedPair = Pair.of(pair.getRight(), pair.getLeft());
    163
    164        return registry != null
    165                && (registry.contains(pair) || registry.contains(swappedPair));
    166    }
    167
    168    /**
    169     * <p>
    170     * Registers the given object pair.
    171     * Used by the reflection methods to avoid infinite loops.
    172     * </p>
    173     *
    174     * @param lhs <code>this</code> object to register
    175     * @param rhs the other object to register
    176     */
    177    private static void register(final Object lhs, final Object rhs) {
    178        Set<Pair<IDKey, IDKey>> registry = getRegistry();
    179        if (registry == null) {
    180            registry = new HashSet<>();
    181            REGISTRY.set(registry);
    182        }
    183        final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
    184        registry.add(pair);
    185    }
    186
    187    /**
    188     * <p>
    189     * Unregisters the given object pair.
    190     * </p>
    191     *
    192     * <p>
    193     * Used by the reflection methods to avoid infinite loops.
    194     *
    195     * @param lhs <code>this</code> object to unregister
    196     * @param rhs the other object to unregister
    197     * @since 3.0
    198     */
    199    private static void unregister(final Object lhs, final Object rhs) {
    200        final Set<Pair<IDKey, IDKey>> registry = getRegistry();
    201        if (registry != null) {
    202            final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
    203            registry.remove(pair);
    204            if (registry.isEmpty()) {
    205                REGISTRY.remove();
    206            }
    207        }
    208    }
    209
    210    /**
    211     * If the fields tested are equals.
    212     * The default value is <code>true</code>.
    213     */
    214    private boolean isEquals = true;
    215
    216    private boolean testTransients = false;
    217    private boolean testRecursive = false;
    218    private List<Class<?>> bypassReflectionClasses;
    219    private Class<?> reflectUpToClass = null;
    220    private String[] excludeFields = null;
    221
    222    /**
    223     * <p>Constructor for EqualsBuilder.</p>
    224     *
    225     * <p>Starts off assuming that equals is <code>true</code>.</p>
    226     * @see Object#equals(Object)
    227     */
    228    public EqualsBuilder() {
    229        // set up default classes to bypass reflection for
    230        bypassReflectionClasses = new ArrayList<>();
    231        bypassReflectionClasses.add(String.class); //hashCode field being lazy but not transient
    232    }
    233
    234    //-------------------------------------------------------------------------
    235
    236    /**
    237     * Set whether to include transient fields when reflectively comparing objects.
    238     * @param testTransients whether to test transient fields
    239     * @return EqualsBuilder - used to chain calls.
    240     * @since 3.6
    241     */
    242    public EqualsBuilder setTestTransients(final boolean testTransients) {
    243        this.testTransients = testTransients;
    244        return this;
    245    }
    246
    247    /**
    248     * Set whether to include transient fields when reflectively comparing objects.
    249     * @param testRecursive  whether to do a recursive test
    250     * @return EqualsBuilder - used to chain calls.
    251     * @since 3.6
    252     */
    253    public EqualsBuilder setTestRecursive(final boolean testRecursive) {
    254        this.testRecursive = testRecursive;
    255        return this;
    256    }
    257
    258    /**
    259     * <p>Set <code>Class</code>es whose instances should be compared by calling their <code>equals</code>
    260     * although being in recursive mode. So the fields of theses classes will not be compared recursively by reflection.</p>
    261     *
    262     * <p>Here you should name classes having non-transient fields which are cache fields being set lazily.<br>
    263     * Prominent example being {@link String} class with its hash code cache field. Due to the importance
    264     * of the <code>String</code> class, it is included in the default bypasses classes. Usually, if you use
    265     * your own set of classes here, remember to include <code>String</code> class, too.</p>
    266     * @param bypassReflectionClasses  classes to bypass reflection test
    267     * @return EqualsBuilder - used to chain calls.
    268     * @since 3.8
    269     */
    270    public EqualsBuilder setBypassReflectionClasses(List<Class<?>> bypassReflectionClasses) {
    271        this.bypassReflectionClasses = bypassReflectionClasses;
    272        return this;
    273    }
    274
    275    /**
    276     * Set the superclass to reflect up to at reflective tests.
    277     * @param reflectUpToClass the super class to reflect up to
    278     * @return EqualsBuilder - used to chain calls.
    279     * @since 3.6
    280     */
    281    public EqualsBuilder setReflectUpToClass(final Class<?> reflectUpToClass) {
    282        this.reflectUpToClass = reflectUpToClass;
    283        return this;
    284    }
    285
    286    /**
    287     * Set field names to be excluded by reflection tests.
    288     * @param excludeFields the fields to exclude
    289     * @return EqualsBuilder - used to chain calls.
    290     * @since 3.6
    291     */
    292    public EqualsBuilder setExcludeFields(final String... excludeFields) {
    293        this.excludeFields = excludeFields;
    294        return this;
    295    }
    296
    297
    298    /**
    299     * <p>This method uses reflection to determine if the two <code>Object</code>s
    300     * are equal.</p>
    301     *
    302     * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
    303     * fields. This means that it will throw a security exception if run under
    304     * a security manager, if the permissions are not set up correctly. It is also
    305     * not as efficient as testing explicitly. Non-primitive fields are compared using
    306     * <code>equals()</code>.</p>
    307     *
    308     * <p>Transient members will be not be tested, as they are likely derived
    309     * fields, and not part of the value of the Object.</p>
    310     *
    311     * <p>Static fields will not be tested. Superclass fields will be included.</p>
    312     *
    313     * @param lhs  <code>this</code> object
    314     * @param rhs  the other object
    315     * @param excludeFields  Collection of String field names to exclude from testing
    316     * @return <code>true</code> if the two Objects have tested equals.
    317     *
    318     * @see EqualsExclude
    319     */
    320    public static boolean reflectionEquals(final Object lhs, final Object rhs, final Collection<String> excludeFields) {
    321        return reflectionEquals(lhs, rhs, ReflectionToStringBuilder.toNoNullStringArray(excludeFields));
    322    }
    323
    324    /**
    325     * <p>This method uses reflection to determine if the two <code>Object</code>s
    326     * are equal.</p>
    327     *
    328     * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
    329     * fields. This means that it will throw a security exception if run under
    330     * a security manager, if the permissions are not set up correctly. It is also
    331     * not as efficient as testing explicitly. Non-primitive fields are compared using
    332     * <code>equals()</code>.</p>
    333     *
    334     * <p>Transient members will be not be tested, as they are likely derived
    335     * fields, and not part of the value of the Object.</p>
    336     *
    337     * <p>Static fields will not be tested. Superclass fields will be included.</p>
    338     *
    339     * @param lhs  <code>this</code> object
    340     * @param rhs  the other object
    341     * @param excludeFields  array of field names to exclude from testing
    342     * @return <code>true</code> if the two Objects have tested equals.
    343     *
    344     * @see EqualsExclude
    345     */
    346    public static boolean reflectionEquals(final Object lhs, final Object rhs, final String... excludeFields) {
    347        return reflectionEquals(lhs, rhs, false, null, excludeFields);
    348    }
    349
    350    /**
    351     * <p>This method uses reflection to determine if the two <code>Object</code>s
    352     * are equal.</p>
    353     *
    354     * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
    355     * fields. This means that it will throw a security exception if run under
    356     * a security manager, if the permissions are not set up correctly. It is also
    357     * not as efficient as testing explicitly. Non-primitive fields are compared using
    358     * <code>equals()</code>.</p>
    359     *
    360     * <p>If the TestTransients parameter is set to <code>true</code>, transient
    361     * members will be tested, otherwise they are ignored, as they are likely
    362     * derived fields, and not part of the value of the <code>Object</code>.</p>
    363     *
    364     * <p>Static fields will not be tested. Superclass fields will be included.</p>
    365     *
    366     * @param lhs  <code>this</code> object
    367     * @param rhs  the other object
    368     * @param testTransients  whether to include transient fields
    369     * @return <code>true</code> if the two Objects have tested equals.
    370     *
    371     * @see EqualsExclude
    372     */
    373    public static boolean reflectionEquals(final Object lhs, final Object rhs, final boolean testTransients) {
    374        return reflectionEquals(lhs, rhs, testTransients, null);
    375    }
    376
    377    /**
    378     * <p>This method uses reflection to determine if the two <code>Object</code>s
    379     * are equal.</p>
    380     *
    381     * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
    382     * fields. This means that it will throw a security exception if run under
    383     * a security manager, if the permissions are not set up correctly. It is also
    384     * not as efficient as testing explicitly. Non-primitive fields are compared using
    385     * <code>equals()</code>.</p>
    386     *
    387     * <p>If the testTransients parameter is set to <code>true</code>, transient
    388     * members will be tested, otherwise they are ignored, as they are likely
    389     * derived fields, and not part of the value of the <code>Object</code>.</p>
    390     *
    391     * <p>Static fields will not be included. Superclass fields will be appended
    392     * up to and including the specified superclass. A null superclass is treated
    393     * as java.lang.Object.</p>
    394     *
    395     * @param lhs  <code>this</code> object
    396     * @param rhs  the other object
    397     * @param testTransients  whether to include transient fields
    398     * @param reflectUpToClass  the superclass to reflect up to (inclusive),
    399     *  may be <code>null</code>
    400     * @param excludeFields  array of field names to exclude from testing
    401     * @return <code>true</code> if the two Objects have tested equals.
    402     *
    403     * @see EqualsExclude
    404     * @since 2.0
    405     */
    406    public static boolean reflectionEquals(final Object lhs, final Object rhs, final boolean testTransients, final Class<?> reflectUpToClass,
    407            final String... excludeFields) {
    408        return reflectionEquals(lhs, rhs, testTransients, reflectUpToClass, false, excludeFields);
    409    }
    410
    411    /**
    412     * <p>This method uses reflection to determine if the two <code>Object</code>s
    413     * are equal.</p>
    414     *
    415     * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
    416     * fields. This means that it will throw a security exception if run under
    417     * a security manager, if the permissions are not set up correctly. It is also
    418     * not as efficient as testing explicitly. Non-primitive fields are compared using
    419     * <code>equals()</code>.</p>
    420     *
    421     * <p>If the testTransients parameter is set to <code>true</code>, transient
    422     * members will be tested, otherwise they are ignored, as they are likely
    423     * derived fields, and not part of the value of the <code>Object</code>.</p>
    424     *
    425     * <p>Static fields will not be included. Superclass fields will be appended
    426     * up to and including the specified superclass. A null superclass is treated
    427     * as java.lang.Object.</p>
    428     *
    429     * <p>If the testRecursive parameter is set to <code>true</code>, non primitive
    430     * (and non primitive wrapper) field types will be compared by
    431     * <code>EqualsBuilder</code> recursively instead of invoking their
    432     * <code>equals()</code> method. Leading to a deep reflection equals test.
    433     *
    434     * @param lhs  <code>this</code> object
    435     * @param rhs  the other object
    436     * @param testTransients  whether to include transient fields
    437     * @param reflectUpToClass  the superclass to reflect up to (inclusive),
    438     *  may be <code>null</code>
    439     * @param testRecursive  whether to call reflection equals on non primitive
    440     *  fields recursively.
    441     * @param excludeFields  array of field names to exclude from testing
    442     * @return <code>true</code> if the two Objects have tested equals.
    443     *
    444     * @see EqualsExclude
    445     * @since 3.6
    446     */
    447    public static boolean reflectionEquals(final Object lhs, final Object rhs, final boolean testTransients, final Class<?> reflectUpToClass,
    448            final boolean testRecursive, final String... excludeFields) {
    449        if (lhs == rhs) {
    450            return true;
    451        }
    452        if (lhs == null || rhs == null) {
    453            return false;
    454        }
    455        return new EqualsBuilder()
    456                    .setExcludeFields(excludeFields)
    457                    .setReflectUpToClass(reflectUpToClass)
    458                    .setTestTransients(testTransients)
    459                    .setTestRecursive(testRecursive)
    460                    .reflectionAppend(lhs, rhs)
    461                    .isEquals();
    462    }
    463
    464    /**
    465     * <p>Tests if two <code>objects</code> by using reflection.</p>
    466     *
    467     * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
    468     * fields. This means that it will throw a security exception if run under
    469     * a security manager, if the permissions are not set up correctly. It is also
    470     * not as efficient as testing explicitly. Non-primitive fields are compared using
    471     * <code>equals()</code>.</p>
    472     *
    473     * <p>If the testTransients field is set to <code>true</code>, transient
    474     * members will be tested, otherwise they are ignored, as they are likely
    475     * derived fields, and not part of the value of the <code>Object</code>.</p>
    476     *
    477     * <p>Static fields will not be included. Superclass fields will be appended
    478     * up to and including the specified superclass in field <code>reflectUpToClass</code>.
    479     * A null superclass is treated as java.lang.Object.</p>
    480     *
    481     * <p>Field names listed in field <code>excludeFields</code> will be ignored.</p>
    482     *
    483     * <p>If either class of the compared objects is contained in
    484     * <code>bypassReflectionClasses</code>, both objects are compared by calling
    485     * the equals method of the left hand object with the right hand object as an argument.</p>
    486     *
    487     * @param lhs  the left hand object
    488     * @param rhs  the left hand object
    489     * @return EqualsBuilder - used to chain calls.
    490     */
    491    public EqualsBuilder reflectionAppend(final Object lhs, final Object rhs) {
    492        if (!isEquals) {
    493            return this;
    494        }
    495        if (lhs == rhs) {
    496            return this;
    497        }
    498        if (lhs == null || rhs == null) {
    499            isEquals = false;
    500            return this;
    501        }
    502
    503        // Find the leaf class since there may be transients in the leaf
    504        // class or in classes between the leaf and root.
    505        // If we are not testing transients or a subclass has no ivars,
    506        // then a subclass can test equals to a superclass.
    507        final Class<?> lhsClass = lhs.getClass();
    508        final Class<?> rhsClass = rhs.getClass();
    509        Class<?> testClass;
    510        if (lhsClass.isInstance(rhs)) {
    511            testClass = lhsClass;
    512            if (!rhsClass.isInstance(lhs)) {
    513                // rhsClass is a subclass of lhsClass
    514                testClass = rhsClass;
    515            }
    516        } else if (rhsClass.isInstance(lhs)) {
    517            testClass = rhsClass;
    518            if (!lhsClass.isInstance(rhs)) {
    519                // lhsClass is a subclass of rhsClass
    520                testClass = lhsClass;
    521            }
    522        } else {
    523            // The two classes are not related.
    524            isEquals = false;
    525            return this;
    526        }
    527
    528        try {
    529            if (testClass.isArray()) {
    530                append(lhs, rhs);
    531            } else {
    532                //If either class is being excluded, call normal object equals method on lhsClass.
    533                if (bypassReflectionClasses != null
    534                        && (bypassReflectionClasses.contains(lhsClass) || bypassReflectionClasses.contains(rhsClass))) {
    535                    isEquals = lhs.equals(rhs);
    536                } else {
    537                    reflectionAppend(lhs, rhs, testClass);
    538                    while (testClass.getSuperclass() != null && testClass != reflectUpToClass) {
    539                        testClass = testClass.getSuperclass();
    540                        reflectionAppend(lhs, rhs, testClass);
    541                    }
    542                }
    543            }
    544        } catch (final IllegalArgumentException e) {
    545            // In this case, we tried to test a subclass vs. a superclass and
    546            // the subclass has ivars or the ivars are transient and
    547            // we are testing transients.
    548            // If a subclass has ivars that we are trying to test them, we get an
    549            // exception and we know that the objects are not equal.
    550            isEquals = false;
    551            return this;
    552        }
    553        return this;
    554    }
    555
    556    /**
    557     * <p>Appends the fields and values defined by the given object of the
    558     * given Class.</p>
    559     *
    560     * @param lhs  the left hand object
    561     * @param rhs  the right hand object
    562     * @param clazz  the class to append details of
    563     */
    564    private void reflectionAppend(
    565        final Object lhs,
    566        final Object rhs,
    567        final Class<?> clazz) {
    568
    569        if (isRegistered(lhs, rhs)) {
    570            return;
    571        }
    572
    573        try {
    574            register(lhs, rhs);
    575            final Field[] fields = clazz.getDeclaredFields();
    576            AccessibleObject.setAccessible(fields, true);
    577            for (int i = 0; i < fields.length && isEquals; i++) {
    578                final Field f = fields[i];
    579                if (!ArrayUtils.contains(excludeFields, f.getName())
    580                    && !f.getName().contains("$")
    581                    && (testTransients || !Modifier.isTransient(f.getModifiers()))
    582                    && !Modifier.isStatic(f.getModifiers())
    583                    && !f.isAnnotationPresent(EqualsExclude.class)) {
    584                    try {
    585                        append(f.get(lhs), f.get(rhs));
    586                    } catch (final IllegalAccessException e) {
    587                        //this can't happen. Would get a Security exception instead
    588                        //throw a runtime exception in case the impossible happens.
    589                        throw new InternalError("Unexpected IllegalAccessException");
    590                    }
    591                }
    592            }
    593        } finally {
    594            unregister(lhs, rhs);
    595        }
    596    }
    597
    598    //-------------------------------------------------------------------------
    599
    600    /**
    601     * <p>Adds the result of <code>super.equals()</code> to this builder.</p>
    602     *
    603     * @param superEquals  the result of calling <code>super.equals()</code>
    604     * @return EqualsBuilder - used to chain calls.
    605     * @since 2.0
    606     */
    607    public EqualsBuilder appendSuper(final boolean superEquals) {
    608        if (!isEquals) {
    609            return this;
    610        }
    611        isEquals = superEquals;
    612        return this;
    613    }
    614
    615    //-------------------------------------------------------------------------
    616
    617    /**
    618     * <p>Test if two <code>Object</code>s are equal using either
    619     * #{@link #reflectionAppend(Object, Object)}, if object are non
    620     * primitives (or wrapper of primitives) or if field <code>testRecursive</code>
    621     * is set to <code>false</code>. Otherwise, using their
    622     * <code>equals</code> method.</p>
    623     *
    624     * @param lhs  the left hand object
    625     * @param rhs  the right hand object
    626     * @return EqualsBuilder - used to chain calls.
    627     */
    628    public EqualsBuilder append(final Object lhs, final Object rhs) {
    629        if (!isEquals) {
    630            return this;
    631        }
    632        if (lhs == rhs) {
    633            return this;
    634        }
    635        if (lhs == null || rhs == null) {
    636            this.setEquals(false);
    637            return this;
    638        }
    639        final Class<?> lhsClass = lhs.getClass();
    640        if (lhsClass.isArray()) {
    641            // factor out array case in order to keep method small enough
    642            // to be inlined
    643            appendArray(lhs, rhs);
    644        } else {
    645            // The simple case, not an array, just test the element
    646            if (testRecursive && !ClassUtils.isPrimitiveOrWrapper(lhsClass)) {
    647                reflectionAppend(lhs, rhs);
    648            } else {
    649                isEquals = lhs.equals(rhs);
    650            }
    651        }
    652        return this;
    653    }
    654
    655    /**
    656     * <p>Test if an <code>Object</code> is equal to an array.</p>
    657     *
    658     * @param lhs  the left hand object, an array
    659     * @param rhs  the right hand object
    660     */
    661    private void appendArray(final Object lhs, final Object rhs) {
    662        // First we compare different dimensions, for example: a boolean[][] to a boolean[]
    663        // then we 'Switch' on type of array, to dispatch to the correct handler
    664        // This handles multi dimensional arrays of the same depth
    665        if (lhs.getClass() != rhs.getClass()) {
    666            this.setEquals(false);
    667        } else if (lhs instanceof long[]) {
    668            append((long[]) lhs, (long[]) rhs);
    669        } else if (lhs instanceof int[]) {
    670            append((int[]) lhs, (int[]) rhs);
    671        } else if (lhs instanceof short[]) {
    672            append((short[]) lhs, (short[]) rhs);
    673        } else if (lhs instanceof char[]) {
    674            append((char[]) lhs, (char[]) rhs);
    675        } else if (lhs instanceof byte[]) {
    676            append((byte[]) lhs, (byte[]) rhs);
    677        } else if (lhs instanceof double[]) {
    678            append((double[]) lhs, (double[]) rhs);
    679        } else if (lhs instanceof float[]) {
    680            append((float[]) lhs, (float[]) rhs);
    681        } else if (lhs instanceof boolean[]) {
    682            append((boolean[]) lhs, (boolean[]) rhs);
    683        } else {
    684            // Not an array of primitives
    685            append((Object[]) lhs, (Object[]) rhs);
    686        }
    687    }
    688
    689    /**
    690     * <p>
    691     * Test if two <code>long</code> s are equal.
    692     * </p>
    693     *
    694     * @param lhs
    695     *                  the left hand <code>long</code>
    696     * @param rhs
    697     *                  the right hand <code>long</code>
    698     * @return EqualsBuilder - used to chain calls.
    699     */
    700    public EqualsBuilder append(final long lhs, final long rhs) {
    701        if (!isEquals) {
    702            return this;
    703        }
    704        isEquals = lhs == rhs;
    705        return this;
    706    }
    707
    708    /**
    709     * <p>Test if two <code>int</code>s are equal.</p>
    710     *
    711     * @param lhs  the left hand <code>int</code>
    712     * @param rhs  the right hand <code>int</code>
    713     * @return EqualsBuilder - used to chain calls.
    714     */
    715    public EqualsBuilder append(final int lhs, final int rhs) {
    716        if (!isEquals) {
    717            return this;
    718        }
    719        isEquals = lhs == rhs;
    720        return this;
    721    }
    722
    723    /**
    724     * <p>Test if two <code>short</code>s are equal.</p>
    725     *
    726     * @param lhs  the left hand <code>short</code>
    727     * @param rhs  the right hand <code>short</code>
    728     * @return EqualsBuilder - used to chain calls.
    729     */
    730    public EqualsBuilder append(final short lhs, final short rhs) {
    731        if (!isEquals) {
    732            return this;
    733        }
    734        isEquals = lhs == rhs;
    735        return this;
    736    }
    737
    738    /**
    739     * <p>Test if two <code>char</code>s are equal.</p>
    740     *
    741     * @param lhs  the left hand <code>char</code>
    742     * @param rhs  the right hand <code>char</code>
    743     * @return EqualsBuilder - used to chain calls.
    744     */
    745    public EqualsBuilder append(final char lhs, final char rhs) {
    746        if (!isEquals) {
    747            return this;
    748        }
    749        isEquals = lhs == rhs;
    750        return this;
    751    }
    752
    753    /**
    754     * <p>Test if two <code>byte</code>s are equal.</p>
    755     *
    756     * @param lhs  the left hand <code>byte</code>
    757     * @param rhs  the right hand <code>byte</code>
    758     * @return EqualsBuilder - used to chain calls.
    759     */
    760    public EqualsBuilder append(final byte lhs, final byte rhs) {
    761        if (!isEquals) {
    762            return this;
    763        }
    764        isEquals = lhs == rhs;
    765        return this;
    766    }
    767
    768    /**
    769     * <p>Test if two <code>double</code>s are equal by testing that the
    770     * pattern of bits returned by <code>doubleToLong</code> are equal.</p>
    771     *
    772     * <p>This handles NaNs, Infinities, and <code>-0.0</code>.</p>
    773     *
    774     * <p>It is compatible with the hash code generated by
    775     * <code>HashCodeBuilder</code>.</p>
    776     *
    777     * @param lhs  the left hand <code>double</code>
    778     * @param rhs  the right hand <code>double</code>
    779     * @return EqualsBuilder - used to chain calls.
    780     */
    781    public EqualsBuilder append(final double lhs, final double rhs) {
    782        if (!isEquals) {
    783            return this;
    784        }
    785        return append(Double.doubleToLongBits(lhs), Double.doubleToLongBits(rhs));
    786    }
    787
    788    /**
    789     * <p>Test if two <code>float</code>s are equal byt testing that the
    790     * pattern of bits returned by doubleToLong are equal.</p>
    791     *
    792     * <p>This handles NaNs, Infinities, and <code>-0.0</code>.</p>
    793     *
    794     * <p>It is compatible with the hash code generated by
    795     * <code>HashCodeBuilder</code>.</p>
    796     *
    797     * @param lhs  the left hand <code>float</code>
    798     * @param rhs  the right hand <code>float</code>
    799     * @return EqualsBuilder - used to chain calls.
    800     */
    801    public EqualsBuilder append(final float lhs, final float rhs) {
    802        if (!isEquals) {
    803            return this;
    804        }
    805        return append(Float.floatToIntBits(lhs), Float.floatToIntBits(rhs));
    806    }
    807
    808    /**
    809     * <p>Test if two <code>booleans</code>s are equal.</p>
    810     *
    811     * @param lhs  the left hand <code>boolean</code>
    812     * @param rhs  the right hand <code>boolean</code>
    813     * @return EqualsBuilder - used to chain calls.
    814      */
    815    public EqualsBuilder append(final boolean lhs, final boolean rhs) {
    816        if (!isEquals) {
    817            return this;
    818        }
    819        isEquals = lhs == rhs;
    820        return this;
    821    }
    822
    823    /**
    824     * <p>Performs a deep comparison of two <code>Object</code> arrays.</p>
    825     *
    826     * <p>This also will be called for the top level of
    827     * multi-dimensional, ragged, and multi-typed arrays.</p>
    828     *
    829     * <p>Note that this method does not compare the type of the arrays; it only
    830     * compares the contents.</p>
    831     *
    832     * @param lhs  the left hand <code>Object[]</code>
    833     * @param rhs  the right hand <code>Object[]</code>
    834     * @return EqualsBuilder - used to chain calls.
    835     */
    836    public EqualsBuilder append(final Object[] lhs, final Object[] rhs) {
    837        if (!isEquals) {
    838            return this;
    839        }
    840        if (lhs == rhs) {
    841            return this;
    842        }
    843        if (lhs == null || rhs == null) {
    844            this.setEquals(false);
    845            return this;
    846        }
    847        if (lhs.length != rhs.length) {
    848            this.setEquals(false);
    849            return this;
    850        }
    851        for (int i = 0; i < lhs.length && isEquals; ++i) {
    852            append(lhs[i], rhs[i]);
    853        }
    854        return this;
    855    }
    856
    857    /**
    858     * <p>Deep comparison of array of <code>long</code>. Length and all
    859     * values are compared.</p>
    860     *
    861     * <p>The method {@link #append(long, long)} is used.</p>
    862     *
    863     * @param lhs  the left hand <code>long[]</code>
    864     * @param rhs  the right hand <code>long[]</code>
    865     * @return EqualsBuilder - used to chain calls.
    866     */
    867    public EqualsBuilder append(final long[] lhs, final long[] rhs) {
    868        if (!isEquals) {
    869            return this;
    870        }
    871        if (lhs == rhs) {
    872            return this;
    873        }
    874        if (lhs == null || rhs == null) {
    875            this.setEquals(false);
    876            return this;
    877        }
    878        if (lhs.length != rhs.length) {
    879            this.setEquals(false);
    880            return this;
    881        }
    882        for (int i = 0; i < lhs.length && isEquals; ++i) {
    883            append(lhs[i], rhs[i]);
    884        }
    885        return this;
    886    }
    887
    888    /**
    889     * <p>Deep comparison of array of <code>int</code>. Length and all
    890     * values are compared.</p>
    891     *
    892     * <p>The method {@link #append(int, int)} is used.</p>
    893     *
    894     * @param lhs  the left hand <code>int[]</code>
    895     * @param rhs  the right hand <code>int[]</code>
    896     * @return EqualsBuilder - used to chain calls.
    897     */
    898    public EqualsBuilder append(final int[] lhs, final int[] rhs) {
    899        if (!isEquals) {
    900            return this;
    901        }
    902        if (lhs == rhs) {
    903            return this;
    904        }
    905        if (lhs == null || rhs == null) {
    906            this.setEquals(false);
    907            return this;
    908        }
    909        if (lhs.length != rhs.length) {
    910            this.setEquals(false);
    911            return this;
    912        }
    913        for (int i = 0; i < lhs.length && isEquals; ++i) {
    914            append(lhs[i], rhs[i]);
    915        }
    916        return this;
    917    }
    918
    919    /**
    920     * <p>Deep comparison of array of <code>short</code>. Length and all
    921     * values are compared.</p>
    922     *
    923     * <p>The method {@link #append(short, short)} is used.</p>
    924     *
    925     * @param lhs  the left hand <code>short[]</code>
    926     * @param rhs  the right hand <code>short[]</code>
    927     * @return EqualsBuilder - used to chain calls.
    928     */
    929    public EqualsBuilder append(final short[] lhs, final short[] rhs) {
    930        if (!isEquals) {
    931            return this;
    932        }
    933        if (lhs == rhs) {
    934            return this;
    935        }
    936        if (lhs == null || rhs == null) {
    937            this.setEquals(false);
    938            return this;
    939        }
    940        if (lhs.length != rhs.length) {
    941            this.setEquals(false);
    942            return this;
    943        }
    944        for (int i = 0; i < lhs.length && isEquals; ++i) {
    945            append(lhs[i], rhs[i]);
    946        }
    947        return this;
    948    }
    949
    950    /**
    951     * <p>Deep comparison of array of <code>char</code>. Length and all
    952     * values are compared.</p>
    953     *
    954     * <p>The method {@link #append(char, char)} is used.</p>
    955     *
    956     * @param lhs  the left hand <code>char[]</code>
    957     * @param rhs  the right hand <code>char[]</code>
    958     * @return EqualsBuilder - used to chain calls.
    959     */
    960    public EqualsBuilder append(final char[] lhs, final char[] rhs) {
    961        if (!isEquals) {
    962            return this;
    963        }
    964        if (lhs == rhs) {
    965            return this;
    966        }
    967        if (lhs == null || rhs == null) {
    968            this.setEquals(false);
    969            return this;
    970        }
    971        if (lhs.length != rhs.length) {
    972            this.setEquals(false);
    973            return this;
    974        }
    975        for (int i = 0; i < lhs.length && isEquals; ++i) {
    976            append(lhs[i], rhs[i]);
    977        }
    978        return this;
    979    }
    980
    981    /**
    982     * <p>Deep comparison of array of <code>byte</code>. Length and all
    983     * values are compared.</p>
    984     *
    985     * <p>The method {@link #append(byte, byte)} is used.</p>
    986     *
    987     * @param lhs  the left hand <code>byte[]</code>
    988     * @param rhs  the right hand <code>byte[]</code>
    989     * @return EqualsBuilder - used to chain calls.
    990     */
    991    public EqualsBuilder append(final byte[] lhs, final byte[] rhs) {
    992        if (!isEquals) {
    993            return this;
    994        }
    995        if (lhs == rhs) {
    996            return this;
    997        }
    998        if (lhs == null || rhs == null) {
    999            this.setEquals(false);
    1000            return this;
    1001        }
    1002        if (lhs.length != rhs.length) {
    1003            this.setEquals(false);
    1004            return this;
    1005        }
    1006        for (int i = 0; i < lhs.length && isEquals; ++i) {
    1007            append(lhs[i], rhs[i]);
    1008        }
    1009        return this;
    1010    }
    1011
    1012    /**
    1013     * <p>Deep comparison of array of <code>double</code>. Length and all
    1014     * values are compared.</p>
    1015     *
    1016     * <p>The method {@link #append(double, double)} is used.</p>
    1017     *
    1018     * @param lhs  the left hand <code>double[]</code>
    1019     * @param rhs  the right hand <code>double[]</code>
    1020     * @return EqualsBuilder - used to chain calls.
    1021     */
    1022    public EqualsBuilder append(final double[] lhs, final double[] rhs) {
    1023        if (!isEquals) {
    1024            return this;
    1025        }
    1026        if (lhs == rhs) {
    1027            return this;
    1028        }
    1029        if (lhs == null || rhs == null) {
    1030            this.setEquals(false);
    1031            return this;
    1032        }
    1033        if (lhs.length != rhs.length) {
    1034            this.setEquals(false);
    1035            return this;
    1036        }
    1037        for (int i = 0; i < lhs.length && isEquals; ++i) {
    1038            append(lhs[i], rhs[i]);
    1039        }
    1040        return this;
    1041    }
    1042
    1043    /**
    1044     * <p>Deep comparison of array of <code>float</code>. Length and all
    1045     * values are compared.</p>
    1046     *
    1047     * <p>The method {@link #append(float, float)} is used.</p>
    1048     *
    1049     * @param lhs  the left hand <code>float[]</code>
    1050     * @param rhs  the right hand <code>float[]</code>
    1051     * @return EqualsBuilder - used to chain calls.
    1052     */
    1053    public EqualsBuilder append(final float[] lhs, final float[] rhs) {
    1054        if (!isEquals) {
    1055            return this;
    1056        }
    1057        if (lhs == rhs) {
    1058            return this;
    1059        }
    1060        if (lhs == null || rhs == null) {
    1061            this.setEquals(false);
    1062            return this;
    1063        }
    1064        if (lhs.length != rhs.length) {
    1065            this.setEquals(false);
    1066            return this;
    1067        }
    1068        for (int i = 0; i < lhs.length && isEquals; ++i) {
    1069            append(lhs[i], rhs[i]);
    1070        }
    1071        return this;
    1072    }
    1073
    1074    /**
    1075     * <p>Deep comparison of array of <code>boolean</code>. Length and all
    1076     * values are compared.</p>
    1077     *
    1078     * <p>The method {@link #append(boolean, boolean)} is used.</p>
    1079     *
    1080     * @param lhs  the left hand <code>boolean[]</code>
    1081     * @param rhs  the right hand <code>boolean[]</code>
    1082     * @return EqualsBuilder - used to chain calls.
    1083     */
    1084    public EqualsBuilder append(final boolean[] lhs, final boolean[] rhs) {
    1085        if (!isEquals) {
    1086            return this;
    1087        }
    1088        if (lhs == rhs) {
    1089            return this;
    1090        }
    1091        if (lhs == null || rhs == null) {
    1092            this.setEquals(false);
    1093            return this;
    1094        }
    1095        if (lhs.length != rhs.length) {
    1096            this.setEquals(false);
    1097            return this;
    1098        }
    1099        for (int i = 0; i < lhs.length && isEquals; ++i) {
    1100            append(lhs[i], rhs[i]);
    1101        }
    1102        return this;
    1103    }
    1104
    1105    /**
    1106     * <p>Returns <code>true</code> if the fields that have been checked
    1107     * are all equal.</p>
    1108     *
    1109     * @return boolean
    1110     */
    1111    public boolean isEquals() {
    1112        return this.isEquals;
    1113    }
    1114
    1115    /**
    1116     * <p>Returns <code>true</code> if the fields that have been checked
    1117     * are all equal.</p>
    1118     *
    1119     * @return <code>true</code> if all of the fields that have been checked
    1120     *         are equal, <code>false</code> otherwise.
    1121     *
    1122     * @since 3.0
    1123     */
    1124    @Override
    1125    public Boolean build() {
    1126        return Boolean.valueOf(isEquals());
    1127    }
    1128
    1129    /**
    1130     * Sets the <code>isEquals</code> value.
    1131     *
    1132     * @param isEquals The value to set.
    1133     * @since 2.1
    1134     */
    1135    protected void setEquals(final boolean isEquals) {
    1136        this.isEquals = isEquals;
    1137    }
    1138
    1139    /**
    1140     * Reset the EqualsBuilder so you can use the same object again
    1141     * @since 2.5
    1142     */
    1143    public void reset() {
    1144        this.isEquals = true;
    1145    }
    1146}