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 * https://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 * Assists in implementing {@link Object#equals(Object)} methods. 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="https://www.oracle.com/java/technologies/effectivejava.html">Effective Java</a> 038 * , by Joshua Bloch. In particular the rule for comparing {@code doubles}, 039 * {@code floats}, and arrays can be tricky. Also, making sure that 040 * {@code equals()} and {@code hashCode()} 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}, uses {@code AccessibleObject.setAccessible} 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()}.</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} methods.</p> 086 * 087 * @since 1.0 088 */ 089public class EqualsBuilder implements Builder<Boolean> { 090 091 /** 092 * A registry of objects used by reflection methods to detect cyclical object references and avoid infinite loops. 093 * 094 * @since 3.0 095 */ 096 private static final ThreadLocal<Set<Pair<IDKey, IDKey>>> REGISTRY = ThreadLocal.withInitial(HashSet::new); 097 098 /* 099 * 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 * @see Object#equals(Object) 371 */ 372 public EqualsBuilder() { 373 // set up default classes to bypass reflection for 374 bypassReflectionClasses = new ArrayList<>(1); 375 bypassReflectionClasses.add(String.class); //hashCode field being lazy but not transient 376 } 377 378 /** 379 * Test if two {@code booleans}s are equal. 380 * 381 * @param lhs the left-hand side {@code boolean} 382 * @param rhs the right-hand side {@code boolean} 383 * @return {@code this} instance. 384 */ 385 public EqualsBuilder append(final boolean lhs, final boolean rhs) { 386 if (!isEquals) { 387 return this; 388 } 389 isEquals = lhs == rhs; 390 return this; 391 } 392 393 /** 394 * Deep comparison of array of {@code boolean}. Length and all 395 * values are compared. 396 * 397 * <p>The method {@link #append(boolean, boolean)} is used.</p> 398 * 399 * @param lhs the left-hand side {@code boolean[]} 400 * @param rhs the right-hand side {@code boolean[]} 401 * @return {@code this} instance. 402 */ 403 public EqualsBuilder append(final boolean[] lhs, final boolean[] rhs) { 404 if (!isEquals) { 405 return this; 406 } 407 if (lhs == rhs) { 408 return this; 409 } 410 if (lhs == null || rhs == null) { 411 setEquals(false); 412 return this; 413 } 414 if (lhs.length != rhs.length) { 415 setEquals(false); 416 return this; 417 } 418 for (int i = 0; i < lhs.length && isEquals; ++i) { 419 append(lhs[i], rhs[i]); 420 } 421 return this; 422 } 423 424 /** 425 * Test if two {@code byte}s are equal. 426 * 427 * @param lhs the left-hand side {@code byte} 428 * @param rhs the right-hand side {@code byte} 429 * @return {@code this} instance. 430 */ 431 public EqualsBuilder append(final byte lhs, final byte rhs) { 432 if (isEquals) { 433 isEquals = lhs == rhs; 434 } 435 return this; 436 } 437 438 /** 439 * Deep comparison of array of {@code byte}. Length and all 440 * values are compared. 441 * 442 * <p>The method {@link #append(byte, byte)} is used.</p> 443 * 444 * @param lhs the left-hand side {@code byte[]} 445 * @param rhs the right-hand side {@code byte[]} 446 * @return {@code this} instance. 447 */ 448 public EqualsBuilder append(final byte[] lhs, final byte[] rhs) { 449 if (!isEquals) { 450 return this; 451 } 452 if (lhs == rhs) { 453 return this; 454 } 455 if (lhs == null || rhs == null) { 456 setEquals(false); 457 return this; 458 } 459 if (lhs.length != rhs.length) { 460 setEquals(false); 461 return this; 462 } 463 for (int i = 0; i < lhs.length && isEquals; ++i) { 464 append(lhs[i], rhs[i]); 465 } 466 return this; 467 } 468 469 /** 470 * Test if two {@code char}s are equal. 471 * 472 * @param lhs the left-hand side {@code char} 473 * @param rhs the right-hand side {@code char} 474 * @return {@code this} instance. 475 */ 476 public EqualsBuilder append(final char lhs, final char rhs) { 477 if (isEquals) { 478 isEquals = lhs == rhs; 479 } 480 return this; 481 } 482 483 /** 484 * Deep comparison of array of {@code char}. Length and all 485 * values are compared. 486 * 487 * <p>The method {@link #append(char, char)} is used.</p> 488 * 489 * @param lhs the left-hand side {@code char[]} 490 * @param rhs the right-hand side {@code char[]} 491 * @return {@code this} instance. 492 */ 493 public EqualsBuilder append(final char[] lhs, final char[] rhs) { 494 if (!isEquals) { 495 return this; 496 } 497 if (lhs == rhs) { 498 return this; 499 } 500 if (lhs == null || rhs == null) { 501 setEquals(false); 502 return this; 503 } 504 if (lhs.length != rhs.length) { 505 setEquals(false); 506 return this; 507 } 508 for (int i = 0; i < lhs.length && isEquals; ++i) { 509 append(lhs[i], rhs[i]); 510 } 511 return this; 512 } 513 514 /** 515 * Test if two {@code double}s are equal by testing that the 516 * pattern of bits returned by {@code doubleToLong} are equal. 517 * 518 * <p>This handles NaNs, Infinities, and {@code -0.0}.</p> 519 * 520 * <p>It is compatible with the hash code generated by 521 * {@link HashCodeBuilder}.</p> 522 * 523 * @param lhs the left-hand side {@code double} 524 * @param rhs the right-hand side {@code double} 525 * @return {@code this} instance. 526 */ 527 public EqualsBuilder append(final double lhs, final double rhs) { 528 if (isEquals) { 529 return append(Double.doubleToLongBits(lhs), Double.doubleToLongBits(rhs)); 530 } 531 return this; 532 } 533 534 /** 535 * Deep comparison of array of {@code double}. Length and all 536 * values are compared. 537 * 538 * <p>The method {@link #append(double, double)} is used.</p> 539 * 540 * @param lhs the left-hand side {@code double[]} 541 * @param rhs the right-hand side {@code double[]} 542 * @return {@code this} instance. 543 */ 544 public EqualsBuilder append(final double[] lhs, final double[] rhs) { 545 if (!isEquals) { 546 return this; 547 } 548 if (lhs == rhs) { 549 return this; 550 } 551 if (lhs == null || rhs == null) { 552 setEquals(false); 553 return this; 554 } 555 if (lhs.length != rhs.length) { 556 setEquals(false); 557 return this; 558 } 559 for (int i = 0; i < lhs.length && isEquals; ++i) { 560 append(lhs[i], rhs[i]); 561 } 562 return this; 563 } 564 565 /** 566 * Test if two {@code float}s are equal by testing that the 567 * pattern of bits returned by doubleToLong are equal. 568 * 569 * <p>This handles NaNs, Infinities, and {@code -0.0}.</p> 570 * 571 * <p>It is compatible with the hash code generated by 572 * {@link HashCodeBuilder}.</p> 573 * 574 * @param lhs the left-hand side {@code float} 575 * @param rhs the right-hand side {@code float} 576 * @return {@code this} instance. 577 */ 578 public EqualsBuilder append(final float lhs, final float rhs) { 579 if (isEquals) { 580 return append(Float.floatToIntBits(lhs), Float.floatToIntBits(rhs)); 581 } 582 return this; 583 } 584 585 /** 586 * Deep comparison of array of {@code float}. Length and all 587 * values are compared. 588 * 589 * <p>The method {@link #append(float, float)} is used.</p> 590 * 591 * @param lhs the left-hand side {@code float[]} 592 * @param rhs the right-hand side {@code float[]} 593 * @return {@code this} instance. 594 */ 595 public EqualsBuilder append(final float[] lhs, final float[] rhs) { 596 if (!isEquals) { 597 return this; 598 } 599 if (lhs == rhs) { 600 return this; 601 } 602 if (lhs == null || rhs == null) { 603 setEquals(false); 604 return this; 605 } 606 if (lhs.length != rhs.length) { 607 setEquals(false); 608 return this; 609 } 610 for (int i = 0; i < lhs.length && isEquals; ++i) { 611 append(lhs[i], rhs[i]); 612 } 613 return this; 614 } 615 616 /** 617 * Test if two {@code int}s are equal. 618 * 619 * @param lhs the left-hand side {@code int} 620 * @param rhs the right-hand side {@code int} 621 * @return {@code this} instance. 622 */ 623 public EqualsBuilder append(final int lhs, final int rhs) { 624 if (isEquals) { 625 isEquals = lhs == rhs; 626 } 627 return this; 628 } 629 630 /** 631 * Deep comparison of array of {@code int}. Length and all 632 * values are compared. 633 * 634 * <p>The method {@link #append(int, int)} is used.</p> 635 * 636 * @param lhs the left-hand side {@code int[]} 637 * @param rhs the right-hand side {@code int[]} 638 * @return {@code this} instance. 639 */ 640 public EqualsBuilder append(final int[] lhs, final int[] rhs) { 641 if (!isEquals) { 642 return this; 643 } 644 if (lhs == rhs) { 645 return this; 646 } 647 if (lhs == null || rhs == null) { 648 setEquals(false); 649 return this; 650 } 651 if (lhs.length != rhs.length) { 652 setEquals(false); 653 return this; 654 } 655 for (int i = 0; i < lhs.length && isEquals; ++i) { 656 append(lhs[i], rhs[i]); 657 } 658 return this; 659 } 660 661 /** 662 * Test if two {@code long}s are equal. 663 * 664 * @param lhs 665 * the left-hand side {@code long} 666 * @param rhs 667 * the right-hand side {@code long} 668 * @return {@code this} instance. 669 */ 670 public EqualsBuilder append(final long lhs, final long rhs) { 671 if (isEquals) { 672 isEquals = lhs == rhs; 673 } 674 return this; 675 } 676 677 /** 678 * Deep comparison of array of {@code long}. Length and all 679 * values are compared. 680 * 681 * <p>The method {@link #append(long, long)} is used.</p> 682 * 683 * @param lhs the left-hand side {@code long[]} 684 * @param rhs the right-hand side {@code long[]} 685 * @return {@code this} instance. 686 */ 687 public EqualsBuilder append(final long[] lhs, final long[] rhs) { 688 if (!isEquals) { 689 return this; 690 } 691 if (lhs == rhs) { 692 return this; 693 } 694 if (lhs == null || rhs == null) { 695 setEquals(false); 696 return this; 697 } 698 if (lhs.length != rhs.length) { 699 setEquals(false); 700 return this; 701 } 702 for (int i = 0; i < lhs.length && isEquals; ++i) { 703 append(lhs[i], rhs[i]); 704 } 705 return this; 706 } 707 708 /** 709 * Test if two {@link Object}s are equal using either 710 * #{@link #reflectionAppend(Object, Object)}, if object are non 711 * primitives (or wrapper of primitives) or if field {@code testRecursive} 712 * is set to {@code false}. Otherwise, using their 713 * {@code equals} method. 714 * 715 * @param lhs the left-hand side object 716 * @param rhs the right-hand side object 717 * @return {@code this} instance. 718 */ 719 public EqualsBuilder append(final Object lhs, final Object rhs) { 720 if (!isEquals) { 721 return this; 722 } 723 if (lhs == rhs) { 724 return this; 725 } 726 if (lhs == null || rhs == null) { 727 setEquals(false); 728 return this; 729 } 730 final Class<?> lhsClass = lhs.getClass(); 731 if (lhsClass.isArray()) { 732 // factor out array case in order to keep method small enough 733 // to be inlined 734 appendArray(lhs, rhs); 735 } else // The simple case, not an array, just test the element 736 if (testRecursive && !ClassUtils.isPrimitiveOrWrapper(lhsClass)) { 737 reflectionAppend(lhs, rhs); 738 } else { 739 isEquals = lhs.equals(rhs); 740 } 741 return this; 742 } 743 744 /** 745 * Performs a deep comparison of two {@link Object} arrays. 746 * 747 * <p>This also will be called for the top level of 748 * multi-dimensional, ragged, and multi-typed arrays.</p> 749 * 750 * <p>Note that this method does not compare the type of the arrays; it only 751 * compares the contents.</p> 752 * 753 * @param lhs the left-hand side {@code Object[]} 754 * @param rhs the right-hand side {@code Object[]} 755 * @return {@code this} instance. 756 */ 757 public EqualsBuilder append(final Object[] lhs, final Object[] rhs) { 758 if (!isEquals) { 759 return this; 760 } 761 if (lhs == rhs) { 762 return this; 763 } 764 if (lhs == null || rhs == null) { 765 setEquals(false); 766 return this; 767 } 768 if (lhs.length != rhs.length) { 769 setEquals(false); 770 return this; 771 } 772 for (int i = 0; i < lhs.length && isEquals; ++i) { 773 append(lhs[i], rhs[i]); 774 } 775 return this; 776 } 777 778 /** 779 * Test if two {@code short}s are equal. 780 * 781 * @param lhs the left-hand side {@code short} 782 * @param rhs the right-hand side {@code short} 783 * @return {@code this} instance. 784 */ 785 public EqualsBuilder append(final short lhs, final short rhs) { 786 if (isEquals) { 787 isEquals = lhs == rhs; 788 } 789 return this; 790 } 791 792 /** 793 * Deep comparison of array of {@code short}. Length and all 794 * values are compared. 795 * 796 * <p>The method {@link #append(short, short)} is used.</p> 797 * 798 * @param lhs the left-hand side {@code short[]} 799 * @param rhs the right-hand side {@code short[]} 800 * @return {@code this} instance. 801 */ 802 public EqualsBuilder append(final short[] lhs, final short[] rhs) { 803 if (!isEquals) { 804 return this; 805 } 806 if (lhs == rhs) { 807 return this; 808 } 809 if (lhs == null || rhs == null) { 810 setEquals(false); 811 return this; 812 } 813 if (lhs.length != rhs.length) { 814 setEquals(false); 815 return this; 816 } 817 for (int i = 0; i < lhs.length && isEquals; ++i) { 818 append(lhs[i], rhs[i]); 819 } 820 return this; 821 } 822 823 /** 824 * Test if an {@link Object} is equal to an array. 825 * 826 * @param lhs the left-hand side object, an array 827 * @param rhs the right-hand side object 828 */ 829 private void appendArray(final Object lhs, final Object rhs) { 830 // First we compare different dimensions, for example: a boolean[][] to a boolean[] 831 // then we 'Switch' on type of array, to dispatch to the correct handler 832 // This handles multidimensional arrays of the same depth 833 if (lhs.getClass() != rhs.getClass()) { 834 setEquals(false); 835 } else if (lhs instanceof long[]) { 836 append((long[]) lhs, (long[]) rhs); 837 } else if (lhs instanceof int[]) { 838 append((int[]) lhs, (int[]) rhs); 839 } else if (lhs instanceof short[]) { 840 append((short[]) lhs, (short[]) rhs); 841 } else if (lhs instanceof char[]) { 842 append((char[]) lhs, (char[]) rhs); 843 } else if (lhs instanceof byte[]) { 844 append((byte[]) lhs, (byte[]) rhs); 845 } else if (lhs instanceof double[]) { 846 append((double[]) lhs, (double[]) rhs); 847 } else if (lhs instanceof float[]) { 848 append((float[]) lhs, (float[]) rhs); 849 } else if (lhs instanceof boolean[]) { 850 append((boolean[]) lhs, (boolean[]) rhs); 851 } else { 852 // Not an array of primitives 853 append((Object[]) lhs, (Object[]) rhs); 854 } 855 } 856 857 /** 858 * Adds the result of {@code super.equals()} to this builder. 859 * 860 * @param superEquals the result of calling {@code super.equals()} 861 * @return {@code this} instance. 862 * @since 2.0 863 */ 864 public EqualsBuilder appendSuper(final boolean superEquals) { 865 if (!isEquals) { 866 return this; 867 } 868 isEquals = superEquals; 869 return this; 870 } 871 872 /** 873 * Returns {@code true} if the fields that have been checked 874 * are all equal. 875 * 876 * @return {@code true} if all of the fields that have been checked 877 * are equal, {@code false} otherwise. 878 * 879 * @since 3.0 880 */ 881 @Override 882 public Boolean build() { 883 return Boolean.valueOf(isEquals()); 884 } 885 886 /** 887 * Returns {@code true} if the fields that have been checked 888 * are all equal. 889 * 890 * @return boolean 891 */ 892 public boolean isEquals() { 893 return isEquals; 894 } 895 896 /** 897 * Tests if two {@code objects} by using reflection. 898 * 899 * <p>It uses {@code AccessibleObject.setAccessible} to gain access to private 900 * fields. This means that it will throw a security exception if run under 901 * a security manager, if the permissions are not set up correctly. It is also 902 * not as efficient as testing explicitly. Non-primitive fields are compared using 903 * {@code equals()}.</p> 904 * 905 * <p>If the testTransients field is set to {@code true}, transient 906 * members will be tested, otherwise they are ignored, as they are likely 907 * derived fields, and not part of the value of the {@link Object}.</p> 908 * 909 * <p>Static fields will not be included. Superclass fields will be appended 910 * up to and including the specified superclass in field {@code reflectUpToClass}. 911 * A null superclass is treated as java.lang.Object.</p> 912 * 913 * <p>Field names listed in field {@code excludeFields} will be ignored.</p> 914 * 915 * <p>If either class of the compared objects is contained in 916 * {@code bypassReflectionClasses}, both objects are compared by calling 917 * the equals method of the left-hand side object with the right-hand side object as an argument.</p> 918 * 919 * @param lhs the left-hand side object 920 * @param rhs the right-hand side object 921 * @return {@code this} instance. 922 */ 923 public EqualsBuilder reflectionAppend(final Object lhs, final Object rhs) { 924 if (!isEquals) { 925 return this; 926 } 927 if (lhs == rhs) { 928 return this; 929 } 930 if (lhs == null || rhs == null) { 931 isEquals = false; 932 return this; 933 } 934 935 // Find the leaf class since there may be transients in the leaf 936 // class or in classes between the leaf and root. 937 // If we are not testing transients or a subclass has no ivars, 938 // then a subclass can test equals to a superclass. 939 final Class<?> lhsClass = lhs.getClass(); 940 final Class<?> rhsClass = rhs.getClass(); 941 Class<?> testClass; 942 if (lhsClass.isInstance(rhs)) { 943 testClass = lhsClass; 944 if (!rhsClass.isInstance(lhs)) { 945 // rhsClass is a subclass of lhsClass 946 testClass = rhsClass; 947 } 948 } else if (rhsClass.isInstance(lhs)) { 949 testClass = rhsClass; 950 if (!lhsClass.isInstance(rhs)) { 951 // lhsClass is a subclass of rhsClass 952 testClass = lhsClass; 953 } 954 } else { 955 // The two classes are not related. 956 isEquals = false; 957 return this; 958 } 959 960 try { 961 if (testClass.isArray()) { 962 append(lhs, rhs); 963 } else //If either class is being excluded, call normal object equals method on lhsClass. 964 if (bypassReflectionClasses != null 965 && (bypassReflectionClasses.contains(lhsClass) || bypassReflectionClasses.contains(rhsClass))) { 966 isEquals = lhs.equals(rhs); 967 } else { 968 reflectionAppend(lhs, rhs, testClass); 969 while (testClass.getSuperclass() != null && testClass != reflectUpToClass) { 970 testClass = testClass.getSuperclass(); 971 reflectionAppend(lhs, rhs, testClass); 972 } 973 } 974 } catch (final IllegalArgumentException e) { 975 // In this case, we tried to test a subclass vs. a superclass and 976 // the subclass has ivars or the ivars are transient and 977 // we are testing transients. 978 // If a subclass has ivars that we are trying to test them, we get an 979 // exception and we know that the objects are not equal. 980 isEquals = false; 981 } 982 return this; 983 } 984 985 /** 986 * Appends the fields and values defined by the given object of the 987 * given Class. 988 * 989 * @param lhs the left-hand side object 990 * @param rhs the right-hand side object 991 * @param clazz the class to append details of 992 */ 993 private void reflectionAppend( 994 final Object lhs, 995 final Object rhs, 996 final Class<?> clazz) { 997 998 if (isRegistered(lhs, rhs)) { 999 return; 1000 } 1001 1002 try { 1003 register(lhs, rhs); 1004 final Field[] fields = clazz.getDeclaredFields(); 1005 AccessibleObject.setAccessible(fields, true); 1006 for (int i = 0; i < fields.length && isEquals; i++) { 1007 final Field field = fields[i]; 1008 if (!ArrayUtils.contains(excludeFields, field.getName()) 1009 && !field.getName().contains("$") 1010 && (testTransients || !Modifier.isTransient(field.getModifiers())) 1011 && !Modifier.isStatic(field.getModifiers()) 1012 && !field.isAnnotationPresent(EqualsExclude.class)) { 1013 append(Reflection.getUnchecked(field, lhs), Reflection.getUnchecked(field, rhs)); 1014 } 1015 } 1016 } finally { 1017 unregister(lhs, rhs); 1018 } 1019 } 1020 1021 /** 1022 * Reset the EqualsBuilder so you can use the same object again. 1023 * 1024 * @since 2.5 1025 */ 1026 public void reset() { 1027 isEquals = true; 1028 } 1029 1030 /** 1031 * Sets {@link Class}es whose instances should be compared by calling their {@code equals} 1032 * although being in recursive mode. So the fields of these classes will not be compared recursively by reflection. 1033 * 1034 * <p>Here you should name classes having non-transient fields which are cache fields being set lazily.<br> 1035 * Prominent example being {@link String} class with its hash code cache field. Due to the importance 1036 * of the {@link String} class, it is included in the default bypasses classes. Usually, if you use 1037 * your own set of classes here, remember to include {@link String} class, too.</p> 1038 * 1039 * @param bypassReflectionClasses classes to bypass reflection test 1040 * @return {@code this} instance. 1041 * @see #setTestRecursive(boolean) 1042 * @since 3.8 1043 */ 1044 public EqualsBuilder setBypassReflectionClasses(final List<Class<?>> bypassReflectionClasses) { 1045 this.bypassReflectionClasses = bypassReflectionClasses; 1046 return this; 1047 } 1048 1049 /** 1050 * Sets the {@code isEquals} value. 1051 * 1052 * @param isEquals The value to set. 1053 * @since 2.1 1054 */ 1055 protected void setEquals(final boolean isEquals) { 1056 this.isEquals = isEquals; 1057 } 1058 1059 /** 1060 * Sets field names to be excluded by reflection tests. 1061 * 1062 * @param excludeFields the fields to exclude 1063 * @return {@code this} instance. 1064 * @since 3.6 1065 */ 1066 public EqualsBuilder setExcludeFields(final String... excludeFields) { 1067 this.excludeFields = excludeFields; 1068 return this; 1069 } 1070 1071 /** 1072 * Sets the superclass to reflect up to at reflective tests. 1073 * 1074 * @param reflectUpToClass the super class to reflect up to 1075 * @return {@code this} instance. 1076 * @since 3.6 1077 */ 1078 public EqualsBuilder setReflectUpToClass(final Class<?> reflectUpToClass) { 1079 this.reflectUpToClass = reflectUpToClass; 1080 return this; 1081 } 1082 1083 /** 1084 * Sets whether to test fields recursively, instead of using their equals method, when reflectively comparing objects. 1085 * String objects, which cache a hash value, are automatically excluded from recursive testing. 1086 * You may specify other exceptions by calling {@link #setBypassReflectionClasses(List)}. 1087 * 1088 * @param testRecursive whether to do a recursive test 1089 * @return {@code this} instance. 1090 * @see #setBypassReflectionClasses(List) 1091 * @since 3.6 1092 */ 1093 public EqualsBuilder setTestRecursive(final boolean testRecursive) { 1094 this.testRecursive = testRecursive; 1095 return this; 1096 } 1097 1098 /** 1099 * Sets whether to include transient fields when reflectively comparing objects. 1100 * 1101 * @param testTransients whether to test transient fields 1102 * @return {@code this} instance. 1103 * @since 3.6 1104 */ 1105 public EqualsBuilder setTestTransients(final boolean testTransients) { 1106 this.testTransients = testTransients; 1107 return this; 1108 } 1109}