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; 018 019import java.io.IOException; 020import java.io.Serializable; 021import java.lang.reflect.Array; 022import java.lang.reflect.InvocationTargetException; 023import java.lang.reflect.Method; 024import java.util.Collection; 025import java.util.Collections; 026import java.util.Comparator; 027import java.util.HashMap; 028import java.util.Map; 029import java.util.TreeSet; 030import java.util.function.Supplier; 031 032import org.apache.commons.lang3.exception.CloneFailedException; 033import org.apache.commons.lang3.mutable.MutableInt; 034import org.apache.commons.lang3.text.StrBuilder; 035 036/** 037 * <p>Operations on {@code Object}.</p> 038 * 039 * <p>This class tries to handle {@code null} input gracefully. 040 * An exception will generally not be thrown for a {@code null} input. 041 * Each method documents its behavior in more detail.</p> 042 * 043 * <p>#ThreadSafe#</p> 044 * @since 1.0 045 */ 046//@Immutable 047@SuppressWarnings("deprecation") // deprecated class StrBuilder is imported 048// because it is part of the signature of deprecated methods 049public class ObjectUtils { 050 051 // Null 052 //----------------------------------------------------------------------- 053 /** 054 * <p>Class used as a null placeholder where {@code null} 055 * has another meaning.</p> 056 * 057 * <p>For example, in a {@code HashMap} the 058 * {@link java.util.HashMap#get(java.lang.Object)} method returns 059 * {@code null} if the {@code Map} contains {@code null} or if there is 060 * no matching key. The {@code Null} placeholder can be used to distinguish 061 * between these two cases.</p> 062 * 063 * <p>Another example is {@code Hashtable}, where {@code null} 064 * cannot be stored.</p> 065 */ 066 public static class Null implements Serializable { 067 /** 068 * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 069 * 070 * @see java.io.Serializable 071 */ 072 private static final long serialVersionUID = 7092611880189329093L; 073 074 /** 075 * Restricted constructor - singleton. 076 */ 077 Null() { 078 super(); 079 } 080 081 /** 082 * <p>Ensure singleton.</p> 083 * 084 * @return the singleton value 085 */ 086 private Object readResolve() { 087 return NULL; 088 } 089 } 090 091 private static final char AT_SIGN = '@'; 092 093 /** 094 * <p>Singleton used as a {@code null} placeholder where 095 * {@code null} has another meaning.</p> 096 * 097 * <p>For example, in a {@code HashMap} the 098 * {@link java.util.HashMap#get(java.lang.Object)} method returns 099 * {@code null} if the {@code Map} contains {@code null} or if there 100 * is no matching key. The {@code Null} placeholder can be used to 101 * distinguish between these two cases.</p> 102 * 103 * <p>Another example is {@code Hashtable}, where {@code null} 104 * cannot be stored.</p> 105 * 106 * <p>This instance is Serializable.</p> 107 */ 108 public static final Null NULL = new Null(); 109 110 /** 111 * Checks if all values in the given array are {@code null}. 112 * 113 * <p> 114 * If all the values are {@code null} or the array is {@code null} 115 * or empty, then {@code true} is returned, otherwise {@code false} is returned. 116 * </p> 117 * 118 * <pre> 119 * ObjectUtils.allNull(*) = false 120 * ObjectUtils.allNull(*, null) = false 121 * ObjectUtils.allNull(null, *) = false 122 * ObjectUtils.allNull(null, null, *, *) = false 123 * ObjectUtils.allNull(null) = true 124 * ObjectUtils.allNull(null, null) = true 125 * </pre> 126 * 127 * @param values the values to test, may be {@code null} or empty 128 * @return {@code true} if all values in the array are {@code null}s, 129 * {@code false} if there is at least one non-null value in the array. 130 * @since 3.11 131 */ 132 public static boolean allNull(final Object... values) { 133 return !anyNotNull(values); 134 } 135 136 /** 137 * Checks if all values in the array are not {@code nulls}. 138 * 139 * <p> 140 * If any value is {@code null} or the array is {@code null} then 141 * {@code false} is returned. If all elements in array are not 142 * {@code null} or the array is empty (contains no elements) {@code true} 143 * is returned. 144 * </p> 145 * 146 * <pre> 147 * ObjectUtils.allNotNull(*) = true 148 * ObjectUtils.allNotNull(*, *) = true 149 * ObjectUtils.allNotNull(null) = false 150 * ObjectUtils.allNotNull(null, null) = false 151 * ObjectUtils.allNotNull(null, *) = false 152 * ObjectUtils.allNotNull(*, null) = false 153 * ObjectUtils.allNotNull(*, *, null, *) = false 154 * </pre> 155 * 156 * @param values the values to test, may be {@code null} or empty 157 * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, 158 * {@code true} if all values in the array are not {@code null}s or array contains no elements. 159 * @since 3.5 160 */ 161 public static boolean allNotNull(final Object... values) { 162 if (values == null) { 163 return false; 164 } 165 166 for (final Object val : values) { 167 if (val == null) { 168 return false; 169 } 170 } 171 172 return true; 173 } 174 175 /** 176 * Checks if any value in the given array is {@code null}. 177 * 178 * <p> 179 * If any of the values are {@code null} or the array is {@code null}, 180 * then {@code true} is returned, otherwise {@code false} is returned. 181 * </p> 182 * 183 * <pre> 184 * ObjectUtils.anyNull(*) = false 185 * ObjectUtils.anyNull(*, *) = false 186 * ObjectUtils.anyNull(null) = true 187 * ObjectUtils.anyNull(null, null) = true 188 * ObjectUtils.anyNull(null, *) = true 189 * ObjectUtils.anyNull(*, null) = true 190 * ObjectUtils.anyNull(*, *, null, *) = true 191 * </pre> 192 * 193 * @param values the values to test, may be {@code null} or empty 194 * @return {@code true} if there is at least one {@code null} value in the array, 195 * {@code false} if all the values are non-null. 196 * If the array is {@code null} or empty, {@code true} is also returned. 197 * @since 3.11 198 */ 199 public static boolean anyNull(final Object... values) { 200 return !allNotNull(values); 201 } 202 203 /** 204 * Checks if any value in the given array is not {@code null}. 205 * 206 * <p> 207 * If all the values are {@code null} or the array is {@code null} 208 * or empty then {@code false} is returned. Otherwise {@code true} is returned. 209 * </p> 210 * 211 * <pre> 212 * ObjectUtils.anyNotNull(*) = true 213 * ObjectUtils.anyNotNull(*, null) = true 214 * ObjectUtils.anyNotNull(null, *) = true 215 * ObjectUtils.anyNotNull(null, null, *, *) = true 216 * ObjectUtils.anyNotNull(null) = false 217 * ObjectUtils.anyNotNull(null, null) = false 218 * </pre> 219 * 220 * @param values the values to test, may be {@code null} or empty 221 * @return {@code true} if there is at least one non-null value in the array, 222 * {@code false} if all values in the array are {@code null}s. 223 * If the array is {@code null} or empty {@code false} is also returned. 224 * @since 3.5 225 */ 226 public static boolean anyNotNull(final Object... values) { 227 return firstNonNull(values) != null; 228 } 229 230 // cloning 231 //----------------------------------------------------------------------- 232 /** 233 * <p>Clone an object.</p> 234 * 235 * @param <T> the type of the object 236 * @param obj the object to clone, null returns null 237 * @return the clone if the object implements {@link Cloneable} otherwise {@code null} 238 * @throws CloneFailedException if the object is cloneable and the clone operation fails 239 * @since 3.0 240 */ 241 public static <T> T clone(final T obj) { 242 if (obj instanceof Cloneable) { 243 final Object result; 244 if (obj.getClass().isArray()) { 245 final Class<?> componentType = obj.getClass().getComponentType(); 246 if (componentType.isPrimitive()) { 247 int length = Array.getLength(obj); 248 result = Array.newInstance(componentType, length); 249 while (length-- > 0) { 250 Array.set(result, length, Array.get(obj, length)); 251 } 252 } else { 253 result = ((Object[]) obj).clone(); 254 } 255 } else { 256 try { 257 final Method clone = obj.getClass().getMethod("clone"); 258 result = clone.invoke(obj); 259 } catch (final NoSuchMethodException e) { 260 throw new CloneFailedException("Cloneable type " 261 + obj.getClass().getName() 262 + " has no clone method", e); 263 } catch (final IllegalAccessException e) { 264 throw new CloneFailedException("Cannot clone Cloneable type " 265 + obj.getClass().getName(), e); 266 } catch (final InvocationTargetException e) { 267 throw new CloneFailedException("Exception cloning Cloneable type " 268 + obj.getClass().getName(), e.getCause()); 269 } 270 } 271 @SuppressWarnings("unchecked") // OK because input is of type T 272 final T checked = (T) result; 273 return checked; 274 } 275 276 return null; 277 } 278 279 /** 280 * <p>Clone an object if possible.</p> 281 * 282 * <p>This method is similar to {@link #clone(Object)}, but will return the provided 283 * instance as the return value instead of {@code null} if the instance 284 * is not cloneable. This is more convenient if the caller uses different 285 * implementations (e.g. of a service) and some of the implementations do not allow concurrent 286 * processing or have state. In such cases the implementation can simply provide a proper 287 * clone implementation and the caller's code does not have to change.</p> 288 * 289 * @param <T> the type of the object 290 * @param obj the object to clone, null returns null 291 * @return the clone if the object implements {@link Cloneable} otherwise the object itself 292 * @throws CloneFailedException if the object is cloneable and the clone operation fails 293 * @since 3.0 294 */ 295 public static <T> T cloneIfPossible(final T obj) { 296 final T clone = clone(obj); 297 return clone == null ? obj : clone; 298 } 299 300 /** 301 * <p>Null safe comparison of Comparables. 302 * {@code null} is assumed to be less than a non-{@code null} value.</p> 303 * 304 * @param <T> type of the values processed by this method 305 * @param c1 the first comparable, may be null 306 * @param c2 the second comparable, may be null 307 * @return a negative value if c1 < c2, zero if c1 = c2 308 * and a positive value if c1 > c2 309 */ 310 public static <T extends Comparable<? super T>> int compare(final T c1, final T c2) { 311 return compare(c1, c2, false); 312 } 313 314 /** 315 * <p>Null safe comparison of Comparables.</p> 316 * 317 * @param <T> type of the values processed by this method 318 * @param c1 the first comparable, may be null 319 * @param c2 the second comparable, may be null 320 * @param nullGreater if true {@code null} is considered greater 321 * than a non-{@code null} value or if false {@code null} is 322 * considered less than a Non-{@code null} value 323 * @return a negative value if c1 < c2, zero if c1 = c2 324 * and a positive value if c1 > c2 325 * @see java.util.Comparator#compare(Object, Object) 326 */ 327 public static <T extends Comparable<? super T>> int compare(final T c1, final T c2, final boolean nullGreater) { 328 if (c1 == c2) { 329 return 0; 330 } else if (c1 == null) { 331 return nullGreater ? 1 : -1; 332 } else if (c2 == null) { 333 return nullGreater ? -1 : 1; 334 } 335 return c1.compareTo(c2); 336 } 337 338 /** 339 * This method returns the provided value unchanged. 340 * This can prevent javac from inlining a constant 341 * field, e.g., 342 * 343 * <pre> 344 * public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true); 345 * </pre> 346 * 347 * This way any jars that refer to this field do not 348 * have to recompile themselves if the field's value 349 * changes at some future date. 350 * 351 * @param v the boolean value to return 352 * @return the boolean v, unchanged 353 * @since 3.2 354 */ 355 public static boolean CONST(final boolean v) { 356 return v; 357 } 358 359 /** 360 * This method returns the provided value unchanged. 361 * This can prevent javac from inlining a constant 362 * field, e.g., 363 * 364 * <pre> 365 * public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127); 366 * </pre> 367 * 368 * This way any jars that refer to this field do not 369 * have to recompile themselves if the field's value 370 * changes at some future date. 371 * 372 * @param v the byte value to return 373 * @return the byte v, unchanged 374 * @since 3.2 375 */ 376 public static byte CONST(final byte v) { 377 return v; 378 } 379 380 /** 381 * This method returns the provided value unchanged. 382 * This can prevent javac from inlining a constant 383 * field, e.g., 384 * 385 * <pre> 386 * public final static char MAGIC_CHAR = ObjectUtils.CONST('a'); 387 * </pre> 388 * 389 * This way any jars that refer to this field do not 390 * have to recompile themselves if the field's value 391 * changes at some future date. 392 * 393 * @param v the char value to return 394 * @return the char v, unchanged 395 * @since 3.2 396 */ 397 public static char CONST(final char v) { 398 return v; 399 } 400 401 /** 402 * This method returns the provided value unchanged. 403 * This can prevent javac from inlining a constant 404 * field, e.g., 405 * 406 * <pre> 407 * public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0); 408 * </pre> 409 * 410 * This way any jars that refer to this field do not 411 * have to recompile themselves if the field's value 412 * changes at some future date. 413 * 414 * @param v the double value to return 415 * @return the double v, unchanged 416 * @since 3.2 417 */ 418 public static double CONST(final double v) { 419 return v; 420 } 421 422 /** 423 * This method returns the provided value unchanged. 424 * This can prevent javac from inlining a constant 425 * field, e.g., 426 * 427 * <pre> 428 * public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f); 429 * </pre> 430 * 431 * This way any jars that refer to this field do not 432 * have to recompile themselves if the field's value 433 * changes at some future date. 434 * 435 * @param v the float value to return 436 * @return the float v, unchanged 437 * @since 3.2 438 */ 439 public static float CONST(final float v) { 440 return v; 441 } 442 443 /** 444 * This method returns the provided value unchanged. 445 * This can prevent javac from inlining a constant 446 * field, e.g., 447 * 448 * <pre> 449 * public final static int MAGIC_INT = ObjectUtils.CONST(123); 450 * </pre> 451 * 452 * This way any jars that refer to this field do not 453 * have to recompile themselves if the field's value 454 * changes at some future date. 455 * 456 * @param v the int value to return 457 * @return the int v, unchanged 458 * @since 3.2 459 */ 460 public static int CONST(final int v) { 461 return v; 462 } 463 464 /** 465 * This method returns the provided value unchanged. 466 * This can prevent javac from inlining a constant 467 * field, e.g., 468 * 469 * <pre> 470 * public final static long MAGIC_LONG = ObjectUtils.CONST(123L); 471 * </pre> 472 * 473 * This way any jars that refer to this field do not 474 * have to recompile themselves if the field's value 475 * changes at some future date. 476 * 477 * @param v the long value to return 478 * @return the long v, unchanged 479 * @since 3.2 480 */ 481 public static long CONST(final long v) { 482 return v; 483 } 484 485 /** 486 * This method returns the provided value unchanged. 487 * This can prevent javac from inlining a constant 488 * field, e.g., 489 * 490 * <pre> 491 * public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123); 492 * </pre> 493 * 494 * This way any jars that refer to this field do not 495 * have to recompile themselves if the field's value 496 * changes at some future date. 497 * 498 * @param v the short value to return 499 * @return the short v, unchanged 500 * @since 3.2 501 */ 502 public static short CONST(final short v) { 503 return v; 504 } 505 506 /** 507 * This method returns the provided value unchanged. 508 * This can prevent javac from inlining a constant 509 * field, e.g., 510 * 511 * <pre> 512 * public final static String MAGIC_STRING = ObjectUtils.CONST("abc"); 513 * </pre> 514 * 515 * This way any jars that refer to this field do not 516 * have to recompile themselves if the field's value 517 * changes at some future date. 518 * 519 * @param <T> the Object type 520 * @param v the genericized Object value to return (typically a String). 521 * @return the genericized Object v, unchanged (typically a String). 522 * @since 3.2 523 */ 524 public static <T> T CONST(final T v) { 525 return v; 526 } 527 528 /** 529 * This method returns the provided value unchanged. 530 * This can prevent javac from inlining a constant 531 * field, e.g., 532 * 533 * <pre> 534 * public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127); 535 * </pre> 536 * 537 * This way any jars that refer to this field do not 538 * have to recompile themselves if the field's value 539 * changes at some future date. 540 * 541 * @param v the byte literal (as an int) value to return 542 * @throws IllegalArgumentException if the value passed to v 543 * is larger than a byte, that is, smaller than -128 or 544 * larger than 127. 545 * @return the byte v, unchanged 546 * @since 3.2 547 */ 548 public static byte CONST_BYTE(final int v) { 549 if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { 550 throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); 551 } 552 return (byte) v; 553 } 554 555 /** 556 * This method returns the provided value unchanged. 557 * This can prevent javac from inlining a constant 558 * field, e.g., 559 * 560 * <pre> 561 * public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127); 562 * </pre> 563 * 564 * This way any jars that refer to this field do not 565 * have to recompile themselves if the field's value 566 * changes at some future date. 567 * 568 * @param v the short literal (as an int) value to return 569 * @throws IllegalArgumentException if the value passed to v 570 * is larger than a short, that is, smaller than -32768 or 571 * larger than 32767. 572 * @return the byte v, unchanged 573 * @since 3.2 574 */ 575 public static short CONST_SHORT(final int v) { 576 if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { 577 throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); 578 } 579 return (short) v; 580 } 581 582 /** 583 * <p>Returns a default value if the object passed is {@code null}.</p> 584 * 585 * <pre> 586 * ObjectUtils.defaultIfNull(null, null) = null 587 * ObjectUtils.defaultIfNull(null, "") = "" 588 * ObjectUtils.defaultIfNull(null, "zz") = "zz" 589 * ObjectUtils.defaultIfNull("abc", *) = "abc" 590 * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE 591 * </pre> 592 * 593 * @param <T> the type of the object 594 * @param object the {@code Object} to test, may be {@code null} 595 * @param defaultValue the default value to return, may be {@code null} 596 * @return {@code object} if it is not {@code null}, defaultValue otherwise 597 * TODO Rename to getIfNull in 4.0 598 */ 599 public static <T> T defaultIfNull(final T object, final T defaultValue) { 600 return object != null ? object : defaultValue; 601 } 602 603 // Null-safe equals/hashCode 604 //----------------------------------------------------------------------- 605 /** 606 * <p>Compares two objects for equality, where either one or both 607 * objects may be {@code null}.</p> 608 * 609 * <pre> 610 * ObjectUtils.equals(null, null) = true 611 * ObjectUtils.equals(null, "") = false 612 * ObjectUtils.equals("", null) = false 613 * ObjectUtils.equals("", "") = true 614 * ObjectUtils.equals(Boolean.TRUE, null) = false 615 * ObjectUtils.equals(Boolean.TRUE, "true") = false 616 * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE) = true 617 * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false 618 * </pre> 619 * 620 * @param object1 the first object, may be {@code null} 621 * @param object2 the second object, may be {@code null} 622 * @return {@code true} if the values of both objects are the same 623 * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will 624 * be removed from future releases. 625 */ 626 @Deprecated 627 public static boolean equals(final Object object1, final Object object2) { 628 if (object1 == object2) { 629 return true; 630 } 631 if (object1 == null || object2 == null) { 632 return false; 633 } 634 return object1.equals(object2); 635 } 636 637 /** 638 * <p>Returns the first value in the array which is not {@code null}. 639 * If all the values are {@code null} or the array is {@code null} 640 * or empty then {@code null} is returned.</p> 641 * 642 * <pre> 643 * ObjectUtils.firstNonNull(null, null) = null 644 * ObjectUtils.firstNonNull(null, "") = "" 645 * ObjectUtils.firstNonNull(null, null, "") = "" 646 * ObjectUtils.firstNonNull(null, "zz") = "zz" 647 * ObjectUtils.firstNonNull("abc", *) = "abc" 648 * ObjectUtils.firstNonNull(null, "xyz", *) = "xyz" 649 * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE 650 * ObjectUtils.firstNonNull() = null 651 * </pre> 652 * 653 * @param <T> the component type of the array 654 * @param values the values to test, may be {@code null} or empty 655 * @return the first value from {@code values} which is not {@code null}, 656 * or {@code null} if there are no non-null values 657 * @since 3.0 658 */ 659 @SafeVarargs 660 public static <T> T firstNonNull(final T... values) { 661 if (values != null) { 662 for (final T val : values) { 663 if (val != null) { 664 return val; 665 } 666 } 667 } 668 return null; 669 } 670 671 /** 672 * <p>Executes the given suppliers in order and returns the first return 673 * value where a value other than {@code null} is returned. 674 * Once a non-{@code null} value is obtained, all following suppliers are 675 * not executed anymore. 676 * If all the return values are {@code null} or no suppliers are provided 677 * then {@code null} is returned.</p> 678 * 679 * <pre> 680 * ObjectUtils.firstNonNullLazy(null, () -> null) = null 681 * ObjectUtils.firstNonNullLazy(() -> null, () -> "") = "" 682 * ObjectUtils.firstNonNullLazy(() -> "", () -> throw new IllegalStateException()) = "" 683 * ObjectUtils.firstNonNullLazy(() -> null, () -> "zz) = "zz" 684 * ObjectUtils.firstNonNullLazy() = null 685 * </pre> 686 * 687 * @param <T> the type of the return values 688 * @param suppliers the suppliers returning the values to test. 689 * {@code null} values are ignored. 690 * Suppliers may return {@code null} or a value of type @{code T} 691 * @return the first return value from {@code suppliers} which is not {@code null}, 692 * or {@code null} if there are no non-null values 693 * @since 3.10 694 */ 695 @SafeVarargs 696 public static <T> T getFirstNonNull(final Supplier<T>... suppliers) { 697 if (suppliers != null) { 698 for (final Supplier<T> supplier : suppliers) { 699 if (supplier != null) { 700 final T value = supplier.get(); 701 if (value != null) { 702 return value; 703 } 704 } 705 } 706 } 707 return null; 708 } 709 710 /** 711 * <p> 712 * Returns the given {@code object} is it is non-null, otherwise returns the Supplier's {@link Supplier#get()} 713 * value. 714 * </p> 715 * 716 * <p> 717 * The caller responsible for thread-safety and exception handling of default value supplier. 718 * </p> 719 * 720 * <pre> 721 * ObjectUtils.getIfNull(null, () -> null) = null 722 * ObjectUtils.getIfNull(null, null) = null 723 * ObjectUtils.getIfNull(null, () -> "") = "" 724 * ObjectUtils.getIfNull(null, () -> "zz") = "zz" 725 * ObjectUtils.getIfNull("abc", *) = "abc" 726 * ObjectUtils.getIfNull(Boolean.TRUE, *) = Boolean.TRUE 727 * </pre> 728 * 729 * @param <T> the type of the object 730 * @param object the {@code Object} to test, may be {@code null} 731 * @param defaultSupplier the default value to return, may be {@code null} 732 * @return {@code object} if it is not {@code null}, {@code defaultValueSupplier.get()} otherwise 733 * @since 3.10 734 */ 735 public static <T> T getIfNull(final T object, final Supplier<T> defaultSupplier) { 736 return object != null ? object : defaultSupplier == null ? null : defaultSupplier.get(); 737 } 738 739 /** 740 * <p>Gets the hash code of an object returning zero when the 741 * object is {@code null}.</p> 742 * 743 * <pre> 744 * ObjectUtils.hashCode(null) = 0 745 * ObjectUtils.hashCode(obj) = obj.hashCode() 746 * </pre> 747 * 748 * @param obj the object to obtain the hash code of, may be {@code null} 749 * @return the hash code of the object, or zero if null 750 * @since 2.1 751 * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be 752 * removed in future releases 753 */ 754 @Deprecated 755 public static int hashCode(final Object obj) { 756 // hashCode(Object) retained for performance, as hash code is often critical 757 return obj == null ? 0 : obj.hashCode(); 758 } 759 760 /** 761 * <p>Gets the hash code for multiple objects.</p> 762 * 763 * <p>This allows a hash code to be rapidly calculated for a number of objects. 764 * The hash code for a single object is the <em>not</em> same as {@link #hashCode(Object)}. 765 * The hash code for multiple objects is the same as that calculated by an 766 * {@code ArrayList} containing the specified objects.</p> 767 * 768 * <pre> 769 * ObjectUtils.hashCodeMulti() = 1 770 * ObjectUtils.hashCodeMulti((Object[]) null) = 1 771 * ObjectUtils.hashCodeMulti(a) = 31 + a.hashCode() 772 * ObjectUtils.hashCodeMulti(a,b) = (31 + a.hashCode()) * 31 + b.hashCode() 773 * ObjectUtils.hashCodeMulti(a,b,c) = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode() 774 * </pre> 775 * 776 * @param objects the objects to obtain the hash code of, may be {@code null} 777 * @return the hash code of the objects, or zero if null 778 * @since 3.0 779 * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be 780 * removed in future releases. 781 */ 782 @Deprecated 783 public static int hashCodeMulti(final Object... objects) { 784 int hash = 1; 785 if (objects != null) { 786 for (final Object object : objects) { 787 final int tmpHash = hashCode(object); 788 hash = hash * 31 + tmpHash; 789 } 790 } 791 return hash; 792 } 793 794 /** 795 * <p>Appends the toString that would be produced by {@code Object} 796 * if a class did not override toString itself. {@code null} 797 * will throw a NullPointerException for either of the two parameters. </p> 798 * 799 * <pre> 800 * ObjectUtils.identityToString(appendable, "") = appendable.append("java.lang.String@1e23" 801 * ObjectUtils.identityToString(appendable, Boolean.TRUE) = appendable.append("java.lang.Boolean@7fa" 802 * ObjectUtils.identityToString(appendable, Boolean.TRUE) = appendable.append("java.lang.Boolean@7fa") 803 * </pre> 804 * 805 * @param appendable the appendable to append to 806 * @param object the object to create a toString for 807 * @throws IOException if an I/O error occurs 808 * @since 3.2 809 */ 810 public static void identityToString(final Appendable appendable, final Object object) throws IOException { 811 Validate.notNull(object, "Cannot get the toString of a null object"); 812 appendable.append(object.getClass().getName()) 813 .append(AT_SIGN) 814 .append(Integer.toHexString(System.identityHashCode(object))); 815 } 816 817 // Identity ToString 818 //----------------------------------------------------------------------- 819 /** 820 * <p>Gets the toString that would be produced by {@code Object} 821 * if a class did not override toString itself. {@code null} 822 * will return {@code null}.</p> 823 * 824 * <pre> 825 * ObjectUtils.identityToString(null) = null 826 * ObjectUtils.identityToString("") = "java.lang.String@1e23" 827 * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa" 828 * </pre> 829 * 830 * @param object the object to create a toString for, may be 831 * {@code null} 832 * @return the default toString text, or {@code null} if 833 * {@code null} passed in 834 */ 835 public static String identityToString(final Object object) { 836 if (object == null) { 837 return null; 838 } 839 final String name = object.getClass().getName(); 840 final String hexString = Integer.toHexString(System.identityHashCode(object)); 841 final StringBuilder builder = new StringBuilder(name.length() + 1 + hexString.length()); 842 // @formatter:off 843 builder.append(name) 844 .append(AT_SIGN) 845 .append(hexString); 846 // @formatter:on 847 return builder.toString(); 848 } 849 850 /** 851 * <p>Appends the toString that would be produced by {@code Object} 852 * if a class did not override toString itself. {@code null} 853 * will throw a NullPointerException for either of the two parameters. </p> 854 * 855 * <pre> 856 * ObjectUtils.identityToString(builder, "") = builder.append("java.lang.String@1e23" 857 * ObjectUtils.identityToString(builder, Boolean.TRUE) = builder.append("java.lang.Boolean@7fa" 858 * ObjectUtils.identityToString(builder, Boolean.TRUE) = builder.append("java.lang.Boolean@7fa") 859 * </pre> 860 * 861 * @param builder the builder to append to 862 * @param object the object to create a toString for 863 * @since 3.2 864 * @deprecated as of 3.6, because StrBuilder was moved to commons-text, 865 * use one of the other {@code identityToString} methods instead 866 */ 867 @Deprecated 868 public static void identityToString(final StrBuilder builder, final Object object) { 869 Validate.notNull(object, "Cannot get the toString of a null object"); 870 final String name = object.getClass().getName(); 871 final String hexString = Integer.toHexString(System.identityHashCode(object)); 872 builder.ensureCapacity(builder.length() + name.length() + 1 + hexString.length()); 873 builder.append(name) 874 .append(AT_SIGN) 875 .append(hexString); 876 } 877 878 /** 879 * <p>Appends the toString that would be produced by {@code Object} 880 * if a class did not override toString itself. {@code null} 881 * will throw a NullPointerException for either of the two parameters. </p> 882 * 883 * <pre> 884 * ObjectUtils.identityToString(buf, "") = buf.append("java.lang.String@1e23" 885 * ObjectUtils.identityToString(buf, Boolean.TRUE) = buf.append("java.lang.Boolean@7fa" 886 * ObjectUtils.identityToString(buf, Boolean.TRUE) = buf.append("java.lang.Boolean@7fa") 887 * </pre> 888 * 889 * @param buffer the buffer to append to 890 * @param object the object to create a toString for 891 * @since 2.4 892 */ 893 public static void identityToString(final StringBuffer buffer, final Object object) { 894 Validate.notNull(object, "Cannot get the toString of a null object"); 895 final String name = object.getClass().getName(); 896 final String hexString = Integer.toHexString(System.identityHashCode(object)); 897 buffer.ensureCapacity(buffer.length() + name.length() + 1 + hexString.length()); 898 buffer.append(name) 899 .append(AT_SIGN) 900 .append(hexString); 901 } 902 903 /** 904 * <p>Appends the toString that would be produced by {@code Object} 905 * if a class did not override toString itself. {@code null} 906 * will throw a NullPointerException for either of the two parameters. </p> 907 * 908 * <pre> 909 * ObjectUtils.identityToString(builder, "") = builder.append("java.lang.String@1e23" 910 * ObjectUtils.identityToString(builder, Boolean.TRUE) = builder.append("java.lang.Boolean@7fa" 911 * ObjectUtils.identityToString(builder, Boolean.TRUE) = builder.append("java.lang.Boolean@7fa") 912 * </pre> 913 * 914 * @param builder the builder to append to 915 * @param object the object to create a toString for 916 * @since 3.2 917 */ 918 public static void identityToString(final StringBuilder builder, final Object object) { 919 Validate.notNull(object, "Cannot get the toString of a null object"); 920 final String name = object.getClass().getName(); 921 final String hexString = Integer.toHexString(System.identityHashCode(object)); 922 builder.ensureCapacity(builder.length() + name.length() + 1 + hexString.length()); 923 builder.append(name) 924 .append(AT_SIGN) 925 .append(hexString); 926 } 927 928 929 // Constants (LANG-816): 930 /* 931 These methods ensure constants are not inlined by javac. 932 For example, typically a developer might declare a constant like so: 933 934 public final static int MAGIC_NUMBER = 5; 935 936 Should a different jar file refer to this, and the MAGIC_NUMBER 937 is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar 938 file will need to recompile itself. This is because javac 939 typically inlines the primitive or String constant directly into 940 the bytecode, and removes the reference to the MAGIC_NUMBER field. 941 942 To help the other jar (so that it does not need to recompile 943 when constants are changed) the original developer can declare 944 their constant using one of the CONST() utility methods, instead: 945 946 public final static int MAGIC_NUMBER = CONST(5); 947 */ 948 949 950 // Empty checks 951 //----------------------------------------------------------------------- 952 /** 953 * <p>Checks if an Object is empty or null.</p> 954 * 955 * The following types are supported: 956 * <ul> 957 * <li>{@link CharSequence}: Considered empty if its length is zero.</li> 958 * <li>{@code Array}: Considered empty if its length is zero.</li> 959 * <li>{@link Collection}: Considered empty if it has zero elements.</li> 960 * <li>{@link Map}: Considered empty if it has zero key-value mappings.</li> 961 * </ul> 962 * 963 * <pre> 964 * ObjectUtils.isEmpty(null) = true 965 * ObjectUtils.isEmpty("") = true 966 * ObjectUtils.isEmpty("ab") = false 967 * ObjectUtils.isEmpty(new int[]{}) = true 968 * ObjectUtils.isEmpty(new int[]{1,2,3}) = false 969 * ObjectUtils.isEmpty(1234) = false 970 * </pre> 971 * 972 * @param object the {@code Object} to test, may be {@code null} 973 * @return {@code true} if the object has a supported type and is empty or null, 974 * {@code false} otherwise 975 * @since 3.9 976 */ 977 public static boolean isEmpty(final Object object) { 978 if (object == null) { 979 return true; 980 } 981 if (object instanceof CharSequence) { 982 return ((CharSequence) object).length() == 0; 983 } 984 if (object.getClass().isArray()) { 985 return Array.getLength(object) == 0; 986 } 987 if (object instanceof Collection<?>) { 988 return ((Collection<?>) object).isEmpty(); 989 } 990 if (object instanceof Map<?, ?>) { 991 return ((Map<?, ?>) object).isEmpty(); 992 } 993 return false; 994 } 995 996 /** 997 * <p>Checks if an Object is not empty and not null.</p> 998 * 999 * The following types are supported: 1000 * <ul> 1001 * <li>{@link CharSequence}: Considered empty if its length is zero.</li> 1002 * <li>{@code Array}: Considered empty if its length is zero.</li> 1003 * <li>{@link Collection}: Considered empty if it has zero elements.</li> 1004 * <li>{@link Map}: Considered empty if it has zero key-value mappings.</li> 1005 * </ul> 1006 * 1007 * <pre> 1008 * ObjectUtils.isNotEmpty(null) = false 1009 * ObjectUtils.isNotEmpty("") = false 1010 * ObjectUtils.isNotEmpty("ab") = true 1011 * ObjectUtils.isNotEmpty(new int[]{}) = false 1012 * ObjectUtils.isNotEmpty(new int[]{1,2,3}) = true 1013 * ObjectUtils.isNotEmpty(1234) = true 1014 * </pre> 1015 * 1016 * @param object the {@code Object} to test, may be {@code null} 1017 * @return {@code true} if the object has an unsupported type or is not empty 1018 * and not null, {@code false} otherwise 1019 * @since 3.9 1020 */ 1021 public static boolean isNotEmpty(final Object object) { 1022 return !isEmpty(object); 1023 } 1024 1025 /** 1026 * <p>Null safe comparison of Comparables.</p> 1027 * 1028 * @param <T> type of the values processed by this method 1029 * @param values the set of comparable values, may be null 1030 * @return 1031 * <ul> 1032 * <li>If any objects are non-null and unequal, the greater object. 1033 * <li>If all objects are non-null and equal, the first. 1034 * <li>If any of the comparables are null, the greater of the non-null objects. 1035 * <li>If all the comparables are null, null is returned. 1036 * </ul> 1037 */ 1038 @SafeVarargs 1039 public static <T extends Comparable<? super T>> T max(final T... values) { 1040 T result = null; 1041 if (values != null) { 1042 for (final T value : values) { 1043 if (compare(value, result, false) > 0) { 1044 result = value; 1045 } 1046 } 1047 } 1048 return result; 1049 } 1050 1051 /** 1052 * Find the "best guess" middle value among comparables. If there is an even 1053 * number of total values, the lower of the two middle values will be returned. 1054 * @param <T> type of values processed by this method 1055 * @param comparator to use for comparisons 1056 * @param items to compare 1057 * @return T at middle position 1058 * @throws NullPointerException if items or comparator is {@code null} 1059 * @throws IllegalArgumentException if items is empty or contains {@code null} values 1060 * @since 3.0.1 1061 */ 1062 @SafeVarargs 1063 public static <T> T median(final Comparator<T> comparator, final T... items) { 1064 Validate.notEmpty(items, "null/empty items"); 1065 Validate.noNullElements(items); 1066 Validate.notNull(comparator, "null comparator"); 1067 final TreeSet<T> sort = new TreeSet<>(comparator); 1068 Collections.addAll(sort, items); 1069 @SuppressWarnings("unchecked") //we know all items added were T instances 1070 final 1071 T result = (T) sort.toArray()[(sort.size() - 1) / 2]; 1072 return result; 1073 } 1074 1075 /** 1076 * Find the "best guess" middle value among comparables. If there is an even 1077 * number of total values, the lower of the two middle values will be returned. 1078 * @param <T> type of values processed by this method 1079 * @param items to compare 1080 * @return T at middle position 1081 * @throws NullPointerException if items is {@code null} 1082 * @throws IllegalArgumentException if items is empty or contains {@code null} values 1083 * @since 3.0.1 1084 */ 1085 @SafeVarargs 1086 public static <T extends Comparable<? super T>> T median(final T... items) { 1087 Validate.notEmpty(items); 1088 Validate.noNullElements(items); 1089 final TreeSet<T> sort = new TreeSet<>(); 1090 Collections.addAll(sort, items); 1091 @SuppressWarnings("unchecked") //we know all items added were T instances 1092 final T result = (T) sort.toArray()[(sort.size() - 1) / 2]; 1093 return result; 1094 } 1095 1096 // Comparable 1097 //----------------------------------------------------------------------- 1098 /** 1099 * <p>Null safe comparison of Comparables.</p> 1100 * 1101 * @param <T> type of the values processed by this method 1102 * @param values the set of comparable values, may be null 1103 * @return 1104 * <ul> 1105 * <li>If any objects are non-null and unequal, the lesser object. 1106 * <li>If all objects are non-null and equal, the first. 1107 * <li>If any of the comparables are null, the lesser of the non-null objects. 1108 * <li>If all the comparables are null, null is returned. 1109 * </ul> 1110 */ 1111 @SafeVarargs 1112 public static <T extends Comparable<? super T>> T min(final T... values) { 1113 T result = null; 1114 if (values != null) { 1115 for (final T value : values) { 1116 if (compare(value, result, true) < 0) { 1117 result = value; 1118 } 1119 } 1120 } 1121 return result; 1122 } 1123 1124 1125 // Mode 1126 //----------------------------------------------------------------------- 1127 /** 1128 * Find the most frequently occurring item. 1129 * 1130 * @param <T> type of values processed by this method 1131 * @param items to check 1132 * @return most populous T, {@code null} if non-unique or no items supplied 1133 * @since 3.0.1 1134 */ 1135 @SafeVarargs 1136 public static <T> T mode(final T... items) { 1137 if (ArrayUtils.isNotEmpty(items)) { 1138 final HashMap<T, MutableInt> occurrences = new HashMap<>(items.length); 1139 for (final T t : items) { 1140 final MutableInt count = occurrences.get(t); 1141 if (count == null) { 1142 occurrences.put(t, new MutableInt(1)); 1143 } else { 1144 count.increment(); 1145 } 1146 } 1147 T result = null; 1148 int max = 0; 1149 for (final Map.Entry<T, MutableInt> e : occurrences.entrySet()) { 1150 final int cmp = e.getValue().intValue(); 1151 if (cmp == max) { 1152 result = null; 1153 } else if (cmp > max) { 1154 max = cmp; 1155 result = e.getKey(); 1156 } 1157 } 1158 return result; 1159 } 1160 return null; 1161 } 1162 1163 /** 1164 * <p>Compares two objects for inequality, where either one or both 1165 * objects may be {@code null}.</p> 1166 * 1167 * <pre> 1168 * ObjectUtils.notEqual(null, null) = false 1169 * ObjectUtils.notEqual(null, "") = true 1170 * ObjectUtils.notEqual("", null) = true 1171 * ObjectUtils.notEqual("", "") = false 1172 * ObjectUtils.notEqual(Boolean.TRUE, null) = true 1173 * ObjectUtils.notEqual(Boolean.TRUE, "true") = true 1174 * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE) = false 1175 * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true 1176 * </pre> 1177 * 1178 * @param object1 the first object, may be {@code null} 1179 * @param object2 the second object, may be {@code null} 1180 * @return {@code false} if the values of both objects are the same 1181 */ 1182 public static boolean notEqual(final Object object1, final Object object2) { 1183 return !equals(object1, object2); 1184 } 1185 1186 // ToString 1187 //----------------------------------------------------------------------- 1188 /** 1189 * <p>Gets the {@code toString} of an {@code Object} returning 1190 * an empty string ("") if {@code null} input.</p> 1191 * 1192 * <pre> 1193 * ObjectUtils.toString(null) = "" 1194 * ObjectUtils.toString("") = "" 1195 * ObjectUtils.toString("bat") = "bat" 1196 * ObjectUtils.toString(Boolean.TRUE) = "true" 1197 * </pre> 1198 * 1199 * @see StringUtils#defaultString(String) 1200 * @see String#valueOf(Object) 1201 * @param obj the Object to {@code toString}, may be null 1202 * @return the passed in Object's toString, or {@code ""} if {@code null} input 1203 * @since 2.0 1204 * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be 1205 * removed in future releases. Note however that said method will return "null" for null references, while this 1206 * method returns an empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} 1207 */ 1208 @Deprecated 1209 public static String toString(final Object obj) { 1210 return obj == null ? StringUtils.EMPTY : obj.toString(); 1211 } 1212 1213 /** 1214 * <p>Gets the {@code toString} of an {@code Object} returning 1215 * a specified text if {@code null} input.</p> 1216 * 1217 * <pre> 1218 * ObjectUtils.toString(null, null) = null 1219 * ObjectUtils.toString(null, "null") = "null" 1220 * ObjectUtils.toString("", "null") = "" 1221 * ObjectUtils.toString("bat", "null") = "bat" 1222 * ObjectUtils.toString(Boolean.TRUE, "null") = "true" 1223 * </pre> 1224 * 1225 * @see StringUtils#defaultString(String,String) 1226 * @see String#valueOf(Object) 1227 * @param obj the Object to {@code toString}, may be null 1228 * @param nullStr the String to return if {@code null} input, may be null 1229 * @return the passed in Object's toString, or {@code nullStr} if {@code null} input 1230 * @since 2.0 1231 * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and 1232 * will be removed in future releases. 1233 */ 1234 @Deprecated 1235 public static String toString(final Object obj, final String nullStr) { 1236 return obj == null ? nullStr : obj.toString(); 1237 } 1238 1239 /** 1240 * <p>Gets the {@code toString} of an {@code Object} returning 1241 * a specified text if {@code null} input.</p> 1242 * 1243 * <pre> 1244 * ObjectUtils.toString(obj, () -> expensive()) 1245 * </pre> 1246 * <pre> 1247 * ObjectUtils.toString(null, () -> expensive()) = result of expensive() 1248 * ObjectUtils.toString(null, () -> expensive()) = result of expensive() 1249 * ObjectUtils.toString("", () -> expensive()) = "" 1250 * ObjectUtils.toString("bat", () -> expensive()) = "bat" 1251 * ObjectUtils.toString(Boolean.TRUE, () -> expensive()) = "true" 1252 * </pre> 1253 * 1254 * @param obj the Object to {@code toString}, may be null 1255 * @param supplier the Supplier of String used on {@code null} input, may be null 1256 * @return the passed in Object's toString, or {@code nullStr} if {@code null} input 1257 * @since 3.11 1258 */ 1259 public static String toString(final Object obj, final Supplier<String> supplier) { 1260 return obj == null ? supplier == null ? null : supplier.get() : obj.toString(); 1261 } 1262 1263 /** 1264 * <p>{@code ObjectUtils} instances should NOT be constructed in 1265 * standard programming. Instead, the static methods on the class should 1266 * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.</p> 1267 * 1268 * <p>This constructor is public to permit tools that require a JavaBean 1269 * instance to operate.</p> 1270 */ 1271 public ObjectUtils() { 1272 super(); 1273 } 1274 1275}