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