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