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