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