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