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