Coverage Report - org.apache.commons.lang3.ObjectUtils
 
Classes in this File Line Coverage Branch Coverage Complexity
ObjectUtils
96%
119/123
98%
81/82
2.758
ObjectUtils$Null
100%
3/3
N/A
2.758
 
 1  
 /*
 2  
  * Licensed to the Apache Software Foundation (ASF) under one or more
 3  
  * contributor license agreements.  See the NOTICE file distributed with
 4  
  * this work for additional information regarding copyright ownership.
 5  
  * The ASF licenses this file to You under the Apache License, Version 2.0
 6  
  * (the "License"); you may not use this file except in compliance with
 7  
  * the License.  You may obtain a copy of the License at
 8  
  *
 9  
  *      http://www.apache.org/licenses/LICENSE-2.0
 10  
  *
 11  
  * Unless required by applicable law or agreed to in writing, software
 12  
  * distributed under the License is distributed on an "AS IS" BASIS,
 13  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 14  
  * See the License for the specific language governing permissions and
 15  
  * limitations under the License.
 16  
  */
 17  
 package org.apache.commons.lang3;
 18  
 
 19  
 import java.io.Serializable;
 20  
 import java.lang.reflect.Array;
 21  
 import java.lang.reflect.InvocationTargetException;
 22  
 import java.lang.reflect.Method;
 23  
 import java.util.Collections;
 24  
 import java.util.Comparator;
 25  
 import java.util.HashMap;
 26  
 import java.util.Map;
 27  
 import java.util.TreeSet;
 28  
 
 29  
 import org.apache.commons.lang3.exception.CloneFailedException;
 30  
 import org.apache.commons.lang3.mutable.MutableInt;
 31  
 
 32  
 /**
 33  
  * <p>Operations on {@code Object}.</p>
 34  
  *
 35  
  * <p>This class tries to handle {@code null} input gracefully.
 36  
  * An exception will generally not be thrown for a {@code null} input.
 37  
  * Each method documents its behaviour in more detail.</p>
 38  
  *
 39  
  * <p>#ThreadSafe#</p>
 40  
  * @since 1.0
 41  
  * @version $Id: ObjectUtils.java 1448293 2013-02-20 16:57:52Z tn $
 42  
  */
 43  
 //@Immutable
 44  
 public class ObjectUtils {
 45  
 
 46  
     /**
 47  
      * <p>Singleton used as a {@code null} placeholder where
 48  
      * {@code null} has another meaning.</p>
 49  
      *
 50  
      * <p>For example, in a {@code HashMap} the
 51  
      * {@link java.util.HashMap#get(java.lang.Object)} method returns
 52  
      * {@code null} if the {@code Map} contains {@code null} or if there
 53  
      * is no matching key. The {@code Null} placeholder can be used to
 54  
      * distinguish between these two cases.</p>
 55  
      *
 56  
      * <p>Another example is {@code Hashtable}, where {@code null}
 57  
      * cannot be stored.</p>
 58  
      *
 59  
      * <p>This instance is Serializable.</p>
 60  
      */
 61  1
     public static final Null NULL = new Null();
 62  
 
 63  
     /**
 64  
      * <p>{@code ObjectUtils} instances should NOT be constructed in
 65  
      * standard programming. Instead, the static methods on the class should
 66  
      * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.</p>
 67  
      *
 68  
      * <p>This constructor is public to permit tools that require a JavaBean
 69  
      * instance to operate.</p>
 70  
      */
 71  
     public ObjectUtils() {
 72  1
         super();
 73  1
     }
 74  
 
 75  
     // Defaulting
 76  
     //-----------------------------------------------------------------------
 77  
     /**
 78  
      * <p>Returns a default value if the object passed is {@code null}.</p>
 79  
      *
 80  
      * <pre>
 81  
      * ObjectUtils.defaultIfNull(null, null)      = null
 82  
      * ObjectUtils.defaultIfNull(null, "")        = ""
 83  
      * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
 84  
      * ObjectUtils.defaultIfNull("abc", *)        = "abc"
 85  
      * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
 86  
      * </pre>
 87  
      *
 88  
      * @param <T> the type of the object
 89  
      * @param object  the {@code Object} to test, may be {@code null}
 90  
      * @param defaultValue  the default value to return, may be {@code null}
 91  
      * @return {@code object} if it is not {@code null}, defaultValue otherwise
 92  
      */
 93  
     public static <T> T defaultIfNull(final T object, final T defaultValue) {
 94  32
         return object != null ? object : defaultValue;
 95  
     }
 96  
 
 97  
     /**
 98  
      * <p>Returns the first value in the array which is not {@code null}.
 99  
      * If all the values are {@code null} or the array is {@code null}
 100  
      * or empty then {@code null} is returned.</p>
 101  
      *
 102  
      * <pre>
 103  
      * ObjectUtils.firstNonNull(null, null)      = null
 104  
      * ObjectUtils.firstNonNull(null, "")        = ""
 105  
      * ObjectUtils.firstNonNull(null, null, "")  = ""
 106  
      * ObjectUtils.firstNonNull(null, "zz")      = "zz"
 107  
      * ObjectUtils.firstNonNull("abc", *)        = "abc"
 108  
      * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
 109  
      * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
 110  
      * ObjectUtils.firstNonNull()                = null
 111  
      * </pre>
 112  
      *
 113  
      * @param <T> the component type of the array
 114  
      * @param values  the values to test, may be {@code null} or empty
 115  
      * @return the first value from {@code values} which is not {@code null},
 116  
      *  or {@code null} if there are no non-null values
 117  
      * @since 3.0
 118  
      */
 119  
     public static <T> T firstNonNull(final T... values) {
 120  10
         if (values != null) {
 121  17
             for (final T val : values) {
 122  12
                 if (val != null) {
 123  4
                     return val;
 124  
                 }
 125  
             }
 126  
         }
 127  6
         return null;
 128  
     }
 129  
 
 130  
     // Null-safe equals/hashCode
 131  
     //-----------------------------------------------------------------------
 132  
     /**
 133  
      * <p>Compares two objects for equality, where either one or both
 134  
      * objects may be {@code null}.</p>
 135  
      *
 136  
      * <pre>
 137  
      * ObjectUtils.equals(null, null)                  = true
 138  
      * ObjectUtils.equals(null, "")                    = false
 139  
      * ObjectUtils.equals("", null)                    = false
 140  
      * ObjectUtils.equals("", "")                      = true
 141  
      * ObjectUtils.equals(Boolean.TRUE, null)          = false
 142  
      * ObjectUtils.equals(Boolean.TRUE, "true")        = false
 143  
      * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
 144  
      * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
 145  
      * </pre>
 146  
      *
 147  
      * @param object1  the first object, may be {@code null}
 148  
      * @param object2  the second object, may be {@code null}
 149  
      * @return {@code true} if the values of both objects are the same
 150  
      */
 151  
     public static boolean equals(final Object object1, final Object object2) {
 152  750
         if (object1 == object2) {
 153  50
             return true;
 154  
         }
 155  700
         if (object1 == null || object2 == null) {
 156  10
             return false;
 157  
         }
 158  690
         return object1.equals(object2);
 159  
     }
 160  
 
 161  
     /**
 162  
      * <p>Compares two objects for inequality, where either one or both
 163  
      * objects may be {@code null}.</p>
 164  
      *
 165  
      * <pre>
 166  
      * ObjectUtils.notEqual(null, null)                  = false
 167  
      * ObjectUtils.notEqual(null, "")                    = true
 168  
      * ObjectUtils.notEqual("", null)                    = true
 169  
      * ObjectUtils.notEqual("", "")                      = false
 170  
      * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
 171  
      * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
 172  
      * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
 173  
      * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
 174  
      * </pre>
 175  
      *
 176  
      * @param object1  the first object, may be {@code null}
 177  
      * @param object2  the second object, may be {@code null}
 178  
      * @return {@code false} if the values of both objects are the same
 179  
      */
 180  
     public static boolean notEqual(final Object object1, final Object object2) {
 181  8
         return ObjectUtils.equals(object1, object2) == false;
 182  
     }
 183  
 
 184  
     /**
 185  
      * <p>Gets the hash code of an object returning zero when the
 186  
      * object is {@code null}.</p>
 187  
      *
 188  
      * <pre>
 189  
      * ObjectUtils.hashCode(null)   = 0
 190  
      * ObjectUtils.hashCode(obj)    = obj.hashCode()
 191  
      * </pre>
 192  
      *
 193  
      * @param obj  the object to obtain the hash code of, may be {@code null}
 194  
      * @return the hash code of the object, or zero if null
 195  
      * @since 2.1
 196  
      */
 197  
     public static int hashCode(final Object obj) {
 198  
         // hashCode(Object) retained for performance, as hash code is often critical
 199  32
         return obj == null ? 0 : obj.hashCode();
 200  
     }
 201  
 
 202  
     /**
 203  
      * <p>Gets the hash code for multiple objects.</p>
 204  
      * 
 205  
      * <p>This allows a hash code to be rapidly calculated for a number of objects.
 206  
      * The hash code for a single object is the <em>not</em> same as {@link #hashCode(Object)}.
 207  
      * The hash code for multiple objects is the same as that calculated by an
 208  
      * {@code ArrayList} containing the specified objects.</p>
 209  
      *
 210  
      * <pre>
 211  
      * ObjectUtils.hashCodeMulti()                 = 1
 212  
      * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
 213  
      * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
 214  
      * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
 215  
      * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
 216  
      * </pre>
 217  
      *
 218  
      * @param objects  the objects to obtain the hash code of, may be {@code null}
 219  
      * @return the hash code of the objects, or zero if null
 220  
      * @since 3.0
 221  
      */
 222  
     public static int hashCodeMulti(final Object... objects) {
 223  6
         int hash = 1;
 224  6
         if (objects != null) {
 225  11
             for (final Object object : objects) {
 226  6
                 hash = hash * 31 + ObjectUtils.hashCode(object);
 227  
             }
 228  
         }
 229  6
         return hash;
 230  
     }
 231  
 
 232  
     // Identity ToString
 233  
     //-----------------------------------------------------------------------
 234  
     /**
 235  
      * <p>Gets the toString that would be produced by {@code Object}
 236  
      * if a class did not override toString itself. {@code null}
 237  
      * will return {@code null}.</p>
 238  
      *
 239  
      * <pre>
 240  
      * ObjectUtils.identityToString(null)         = null
 241  
      * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
 242  
      * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
 243  
      * </pre>
 244  
      *
 245  
      * @param object  the object to create a toString for, may be
 246  
      *  {@code null}
 247  
      * @return the default toString text, or {@code null} if
 248  
      *  {@code null} passed in
 249  
      */
 250  
     public static String identityToString(final Object object) {
 251  3
         if (object == null) {
 252  1
             return null;
 253  
         }
 254  2
         final StringBuffer buffer = new StringBuffer();
 255  2
         identityToString(buffer, object);
 256  2
         return buffer.toString();
 257  
     }
 258  
 
 259  
     /**
 260  
      * <p>Appends the toString that would be produced by {@code Object}
 261  
      * if a class did not override toString itself. {@code null}
 262  
      * will throw a NullPointerException for either of the two parameters. </p>
 263  
      *
 264  
      * <pre>
 265  
      * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
 266  
      * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
 267  
      * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
 268  
      * </pre>
 269  
      *
 270  
      * @param buffer  the buffer to append to
 271  
      * @param object  the object to create a toString for
 272  
      * @since 2.4
 273  
      */
 274  
     public static void identityToString(final StringBuffer buffer, final Object object) {
 275  19
         if (object == null) {
 276  1
             throw new NullPointerException("Cannot get the toString of a null identity");
 277  
         }
 278  18
         buffer.append(object.getClass().getName())
 279  
               .append('@')
 280  
               .append(Integer.toHexString(System.identityHashCode(object)));
 281  17
     }
 282  
 
 283  
     // ToString
 284  
     //-----------------------------------------------------------------------
 285  
     /**
 286  
      * <p>Gets the {@code toString} of an {@code Object} returning
 287  
      * an empty string ("") if {@code null} input.</p>
 288  
      *
 289  
      * <pre>
 290  
      * ObjectUtils.toString(null)         = ""
 291  
      * ObjectUtils.toString("")           = ""
 292  
      * ObjectUtils.toString("bat")        = "bat"
 293  
      * ObjectUtils.toString(Boolean.TRUE) = "true"
 294  
      * </pre>
 295  
      *
 296  
      * @see StringUtils#defaultString(String)
 297  
      * @see String#valueOf(Object)
 298  
      * @param obj  the Object to {@code toString}, may be null
 299  
      * @return the passed in Object's toString, or {@code ""} if {@code null} input
 300  
      * @since 2.0
 301  
      */
 302  
     public static String toString(final Object obj) {
 303  26
         return obj == null ? "" : obj.toString();
 304  
     }
 305  
 
 306  
     /**
 307  
      * <p>Gets the {@code toString} of an {@code Object} returning
 308  
      * a specified text if {@code null} input.</p>
 309  
      *
 310  
      * <pre>
 311  
      * ObjectUtils.toString(null, null)           = null
 312  
      * ObjectUtils.toString(null, "null")         = "null"
 313  
      * ObjectUtils.toString("", "null")           = ""
 314  
      * ObjectUtils.toString("bat", "null")        = "bat"
 315  
      * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
 316  
      * </pre>
 317  
      *
 318  
      * @see StringUtils#defaultString(String,String)
 319  
      * @see String#valueOf(Object)
 320  
      * @param obj  the Object to {@code toString}, may be null
 321  
      * @param nullStr  the String to return if {@code null} input, may be null
 322  
      * @return the passed in Object's toString, or {@code nullStr} if {@code null} input
 323  
      * @since 2.0
 324  
      */
 325  
     public static String toString(final Object obj, final String nullStr) {
 326  2
         return obj == null ? nullStr : obj.toString();
 327  
     }
 328  
 
 329  
     // Comparable
 330  
     //-----------------------------------------------------------------------
 331  
     /**
 332  
      * <p>Null safe comparison of Comparables.</p>
 333  
      *
 334  
      * @param <T> type of the values processed by this method
 335  
      * @param values the set of comparable values, may be null
 336  
      * @return
 337  
      *  <ul>
 338  
      *   <li>If any objects are non-null and unequal, the lesser object.
 339  
      *   <li>If all objects are non-null and equal, the first.
 340  
      *   <li>If any of the comparables are null, the lesser of the non-null objects.
 341  
      *   <li>If all the comparables are null, null is returned.
 342  
      *  </ul>
 343  
      */
 344  
     public static <T extends Comparable<? super T>> T min(final T... values) {
 345  11
         T result = null;
 346  11
         if (values != null) {
 347  32
             for (final T value : values) {
 348  22
                 if (compare(value, result, true) < 0) {
 349  10
                     result = value;
 350  
                 }
 351  
             }
 352  
         }
 353  11
         return result;
 354  
     }
 355  
 
 356  
     /**
 357  
      * <p>Null safe comparison of Comparables.</p>
 358  
      *
 359  
      * @param <T> type of the values processed by this method
 360  
      * @param values the set of comparable values, may be null
 361  
      * @return
 362  
      *  <ul>
 363  
      *   <li>If any objects are non-null and unequal, the greater object.
 364  
      *   <li>If all objects are non-null and equal, the first.
 365  
      *   <li>If any of the comparables are null, the greater of the non-null objects.
 366  
      *   <li>If all the comparables are null, null is returned.
 367  
      *  </ul>
 368  
      */
 369  
     public static <T extends Comparable<? super T>> T max(final T... values) {
 370  11
         T result = null;
 371  11
         if (values != null) {
 372  32
             for (final T value : values) {
 373  22
                 if (compare(value, result, false) > 0) {
 374  10
                     result = value;
 375  
                 }
 376  
             }
 377  
         }
 378  11
         return result;
 379  
     }
 380  
 
 381  
     /**
 382  
      * <p>Null safe comparison of Comparables.
 383  
      * {@code null} is assumed to be less than a non-{@code null} value.</p>
 384  
      *
 385  
      * @param <T> type of the values processed by this method
 386  
      * @param c1  the first comparable, may be null
 387  
      * @param c2  the second comparable, may be null
 388  
      * @return a negative value if c1 < c2, zero if c1 = c2
 389  
      *  and a positive value if c1 > c2
 390  
      */
 391  
     public static <T extends Comparable<? super T>> int compare(final T c1, final T c2) {
 392  4
         return compare(c1, c2, false);
 393  
     }
 394  
 
 395  
     /**
 396  
      * <p>Null safe comparison of Comparables.</p>
 397  
      *
 398  
      * @param <T> type of the values processed by this method
 399  
      * @param c1  the first comparable, may be null
 400  
      * @param c2  the second comparable, may be null
 401  
      * @param nullGreater if true {@code null} is considered greater
 402  
      *  than a non-{@code null} value or if false {@code null} is
 403  
      *  considered less than a Non-{@code null} value
 404  
      * @return a negative value if c1 < c2, zero if c1 = c2
 405  
      *  and a positive value if c1 > c2
 406  
      * @see java.util.Comparator#compare(Object, Object)
 407  
      */
 408  
     public static <T extends Comparable<? super T>> int compare(final T c1, final T c2, final boolean nullGreater) {
 409  52
         if (c1 == c2) {
 410  14
             return 0;
 411  38
         } else if (c1 == null) {
 412  8
             return nullGreater ? 1 : -1;
 413  30
         } else if (c2 == null) {
 414  18
             return nullGreater ? -1 : 1;
 415  
         }
 416  12
         return c1.compareTo(c2);
 417  
     }
 418  
 
 419  
     /**
 420  
      * Find the "best guess" middle value among comparables. If there is an even
 421  
      * number of total values, the lower of the two middle values will be returned.
 422  
      * @param <T> type of values processed by this method
 423  
      * @param items to compare
 424  
      * @return T at middle position
 425  
      * @throws NullPointerException if items is {@code null}
 426  
      * @throws IllegalArgumentException if items is empty or contains {@code null} values
 427  
      * @since 3.0.1
 428  
      */
 429  
     public static <T extends Comparable<? super T>> T median(final T... items) {
 430  10
         Validate.notEmpty(items);
 431  8
         Validate.noNullElements(items);
 432  8
         final TreeSet<T> sort = new TreeSet<T>();
 433  8
         Collections.addAll(sort, items);
 434  
         @SuppressWarnings("unchecked") //we know all items added were T instances
 435  
         final
 436  8
         T result = (T) sort.toArray()[(sort.size() - 1) / 2];
 437  8
         return result;
 438  
     }
 439  
 
 440  
     /**
 441  
      * Find the "best guess" middle value among comparables. If there is an even
 442  
      * number of total values, the lower of the two middle values will be returned.
 443  
      * @param <T> type of values processed by this method
 444  
      * @param comparator to use for comparisons
 445  
      * @param items to compare
 446  
      * @return T at middle position
 447  
      * @throws NullPointerException if items or comparator is {@code null}
 448  
      * @throws IllegalArgumentException if items is empty or contains {@code null} values
 449  
      * @since 3.0.1
 450  
      */
 451  
     public static <T> T median(final Comparator<T> comparator, final T... items) {
 452  8
         Validate.notEmpty(items, "null/empty items");
 453  6
         Validate.noNullElements(items);
 454  6
         Validate.notNull(comparator, "null comparator");
 455  5
         final TreeSet<T> sort = new TreeSet<T>(comparator);
 456  5
         Collections.addAll(sort, items);
 457  
         @SuppressWarnings("unchecked") //we know all items added were T instances
 458  
         final
 459  5
         T result = (T) sort.toArray()[(sort.size() - 1) / 2];
 460  5
         return result;
 461  
     }
 462  
 
 463  
     // Mode
 464  
     //-----------------------------------------------------------------------
 465  
     /**
 466  
      * Find the most frequently occurring item.
 467  
      * 
 468  
      * @param <T> type of values processed by this method
 469  
      * @param items to check
 470  
      * @return most populous T, {@code null} if non-unique or no items supplied
 471  
      * @since 3.0.1
 472  
      */
 473  
     public static <T> T mode(final T... items) {
 474  6
         if (ArrayUtils.isNotEmpty(items)) {
 475  4
             final HashMap<T, MutableInt> occurrences = new HashMap<T, MutableInt>(items.length);
 476  22
             for (final T t : items) {
 477  18
                 final MutableInt count = occurrences.get(t);
 478  18
                 if (count == null) {
 479  14
                     occurrences.put(t, new MutableInt(1));
 480  
                 } else {
 481  4
                     count.increment();
 482  
                 }
 483  
             }
 484  4
             T result = null;
 485  4
             int max = 0;
 486  4
             for (final Map.Entry<T, MutableInt> e : occurrences.entrySet()) {
 487  14
                 final int cmp = e.getValue().intValue();
 488  14
                 if (cmp == max) {
 489  4
                     result = null;
 490  10
                 } else if (cmp > max) {
 491  5
                     max = cmp;
 492  5
                     result = e.getKey();
 493  
                 }
 494  14
             }
 495  4
             return result;
 496  
         }
 497  2
         return null;
 498  
     }
 499  
 
 500  
     // cloning
 501  
     //-----------------------------------------------------------------------
 502  
     /**
 503  
      * <p>Clone an object.</p>
 504  
      *
 505  
      * @param <T> the type of the object
 506  
      * @param obj  the object to clone, null returns null
 507  
      * @return the clone if the object implements {@link Cloneable} otherwise {@code null}
 508  
      * @throws CloneFailedException if the object is cloneable and the clone operation fails
 509  
      * @since 3.0
 510  
      */
 511  
     public static <T> T clone(final T obj) {
 512  8
         if (obj instanceof Cloneable) {
 513  
             final Object result;
 514  6
             if (obj.getClass().isArray()) {
 515  2
                 final Class<?> componentType = obj.getClass().getComponentType();
 516  2
                 if (!componentType.isPrimitive()) {
 517  1
                     result = ((Object[]) obj).clone();
 518  
                 } else {
 519  1
                     int length = Array.getLength(obj);
 520  1
                     result = Array.newInstance(componentType, length);
 521  2
                     while (length-- > 0) {
 522  1
                         Array.set(result, length, Array.get(obj, length));
 523  
                     }
 524  
                 }
 525  2
             } else {
 526  
                 try {
 527  4
                     final Method clone = obj.getClass().getMethod("clone");
 528  2
                     result = clone.invoke(obj);
 529  2
                 } catch (final NoSuchMethodException e) {
 530  2
                     throw new CloneFailedException("Cloneable type "
 531  
                         + obj.getClass().getName()
 532  
                         + " has no clone method", e);
 533  0
                 } catch (final IllegalAccessException e) {
 534  0
                     throw new CloneFailedException("Cannot clone Cloneable type "
 535  
                         + obj.getClass().getName(), e);
 536  0
                 } catch (final InvocationTargetException e) {
 537  0
                     throw new CloneFailedException("Exception cloning Cloneable type "
 538  
                         + obj.getClass().getName(), e.getCause());
 539  2
                 }
 540  
             }
 541  
             @SuppressWarnings("unchecked") // OK because input is of type T
 542  4
             final T checked = (T) result;
 543  4
             return checked;
 544  
         }
 545  
 
 546  2
         return null;
 547  
     }
 548  
 
 549  
     /**
 550  
      * <p>Clone an object if possible.</p>
 551  
      *
 552  
      * <p>This method is similar to {@link #clone(Object)}, but will return the provided
 553  
      * instance as the return value instead of {@code null} if the instance
 554  
      * is not cloneable. This is more convenient if the caller uses different
 555  
      * implementations (e.g. of a service) and some of the implementations do not allow concurrent
 556  
      * processing or have state. In such cases the implementation can simply provide a proper
 557  
      * clone implementation and the caller's code does not have to change.</p>
 558  
      *
 559  
      * @param <T> the type of the object
 560  
      * @param obj  the object to clone, null returns null
 561  
      * @return the clone if the object implements {@link Cloneable} otherwise the object itself
 562  
      * @throws CloneFailedException if the object is cloneable and the clone operation fails
 563  
      * @since 3.0
 564  
      */
 565  
     public static <T> T cloneIfPossible(final T obj) {
 566  3
         final T clone = clone(obj);
 567  2
         return clone == null ? obj : clone;
 568  
     }
 569  
 
 570  
     // Null
 571  
     //-----------------------------------------------------------------------
 572  
     /**
 573  
      * <p>Class used as a null placeholder where {@code null}
 574  
      * has another meaning.</p>
 575  
      *
 576  
      * <p>For example, in a {@code HashMap} the
 577  
      * {@link java.util.HashMap#get(java.lang.Object)} method returns
 578  
      * {@code null} if the {@code Map} contains {@code null} or if there is
 579  
      * no matching key. The {@code Null} placeholder can be used to distinguish
 580  
      * between these two cases.</p>
 581  
      *
 582  
      * <p>Another example is {@code Hashtable}, where {@code null}
 583  
      * cannot be stored.</p>
 584  
      */
 585  
     public static class Null implements Serializable {
 586  
         /**
 587  
          * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0
 588  
          *
 589  
          * @see java.io.Serializable
 590  
          */
 591  
         private static final long serialVersionUID = 7092611880189329093L;
 592  
 
 593  
         /**
 594  
          * Restricted constructor - singleton.
 595  
          */
 596  
         Null() {
 597  1
             super();
 598  1
         }
 599  
 
 600  
         /**
 601  
          * <p>Ensure singleton.</p>
 602  
          *
 603  
          * @return the singleton value
 604  
          */
 605  
         private Object readResolve() {
 606  1
             return ObjectUtils.NULL;
 607  
         }
 608  
     }
 609  
 
 610  
 
 611  
     // Constants (LANG-816):
 612  
     /*
 613  
         These methods ensure constants are not inlined by javac.
 614  
         For example, typically a developer might declare a constant like so:
 615  
 
 616  
             public final static int MAGIC_NUMBER = 5;
 617  
 
 618  
         Should a different jar file refer to this, and the MAGIC_NUMBER
 619  
         is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar
 620  
         file will need to recompile itself.  This is because javac
 621  
         typically inlines the primitive or String constant directly into
 622  
         the bytecode, and removes the reference to the MAGIC_NUMBER field.
 623  
 
 624  
         To help the other jar (so that it does not need to recompile
 625  
         when constants are changed) the original developer can declare
 626  
         their constant using one of the CONST() utility methods, instead:
 627  
 
 628  
             public final static int MAGIC_NUMBER = CONST(5);
 629  
      */
 630  
 
 631  
 
 632  
     /**
 633  
      * This method returns the provided value unchanged.
 634  
      * This can prevent javac from inlining a constant
 635  
      * field, e.g.,
 636  
      *
 637  
      * <pre>
 638  
      *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
 639  
      * </pre>
 640  
      *
 641  
      * This way any jars that refer to this field do not
 642  
      * have to recompile themselves if the field's value
 643  
      * changes at some future date.
 644  
      *
 645  
      * @param v the boolean value to return
 646  
      * @return the boolean v, unchanged
 647  
      */
 648  2
     public static boolean CONST(final boolean v) { return v; }
 649  
 
 650  
     /**
 651  
      * This method returns the provided value unchanged.
 652  
      * This can prevent javac from inlining a constant
 653  
      * field, e.g.,
 654  
      *
 655  
      * <pre>
 656  
      *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
 657  
      * </pre>
 658  
      *
 659  
      * This way any jars that refer to this field do not
 660  
      * have to recompile themselves if the field's value
 661  
      * changes at some future date.
 662  
      *
 663  
      * @param v the byte value to return
 664  
      * @return the byte v, unchanged
 665  
      */
 666  2
     public static byte CONST(final byte v) { return v; }
 667  
 
 668  
     /**
 669  
      * This method returns the provided value unchanged.
 670  
      * This can prevent javac from inlining a constant
 671  
      * field, e.g.,
 672  
      *
 673  
      * <pre>
 674  
      *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
 675  
      * </pre>
 676  
      *
 677  
      * This way any jars that refer to this field do not
 678  
      * have to recompile themselves if the field's value
 679  
      * changes at some future date.
 680  
      *
 681  
      * @param v the byte literal (as an int) value to return
 682  
      * @throws IllegalArgumentException if the value passed to v
 683  
      *         is larger than a byte, that is, smaller than -128 or
 684  
      *         larger than 127.
 685  
      * @return the byte v, unchanged
 686  
      */
 687  
     public static byte CONST_BYTE(final int v) throws IllegalArgumentException {
 688  4
         if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) {
 689  3
             throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]");
 690  
         }
 691  1
         return (byte) v;
 692  
     }
 693  
 
 694  
     /**
 695  
      * This method returns the provided value unchanged.
 696  
      * This can prevent javac from inlining a constant
 697  
      * field, e.g.,
 698  
      *
 699  
      * <pre>
 700  
      *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
 701  
      * </pre>
 702  
      *
 703  
      * This way any jars that refer to this field do not
 704  
      * have to recompile themselves if the field's value
 705  
      * changes at some future date.
 706  
      *
 707  
      * @param v the char value to return
 708  
      * @return the char v, unchanged
 709  
      */
 710  2
     public static char CONST(final char v) { return v; }
 711  
 
 712  
     /**
 713  
      * This method returns the provided value unchanged.
 714  
      * This can prevent javac from inlining a constant
 715  
      * field, e.g.,
 716  
      *
 717  
      * <pre>
 718  
      *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
 719  
      * </pre>
 720  
      *
 721  
      * This way any jars that refer to this field do not
 722  
      * have to recompile themselves if the field's value
 723  
      * changes at some future date.
 724  
      *
 725  
      * @param v the short value to return
 726  
      * @return the short v, unchanged
 727  
      */
 728  2
     public static short CONST(final short v) { return v; }
 729  
 
 730  
     /**
 731  
      * This method returns the provided value unchanged.
 732  
      * This can prevent javac from inlining a constant
 733  
      * field, e.g.,
 734  
      *
 735  
      * <pre>
 736  
      *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
 737  
      * </pre>
 738  
      *
 739  
      * This way any jars that refer to this field do not
 740  
      * have to recompile themselves if the field's value
 741  
      * changes at some future date.
 742  
      *
 743  
      * @param v the short literal (as an int) value to return
 744  
      * @throws IllegalArgumentException if the value passed to v
 745  
      *         is larger than a short, that is, smaller than -32768 or
 746  
      *         larger than 32767.
 747  
      * @return the byte v, unchanged
 748  
      */
 749  
     public static short CONST_SHORT(final int v) throws IllegalArgumentException {
 750  2
         if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) {
 751  1
             throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]");
 752  
         }
 753  1
         return (short) v;
 754  
     }
 755  
 
 756  
 
 757  
     /**
 758  
      * This method returns the provided value unchanged.
 759  
      * This can prevent javac from inlining a constant
 760  
      * field, e.g.,
 761  
      *
 762  
      * <pre>
 763  
      *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
 764  
      * </pre>
 765  
      *
 766  
      * This way any jars that refer to this field do not
 767  
      * have to recompile themselves if the field's value
 768  
      * changes at some future date.
 769  
      *
 770  
      * @param v the int value to return
 771  
      * @return the int v, unchanged
 772  
      */
 773  3
     public static int CONST(final int v) { return v; }
 774  
 
 775  
     /**
 776  
      * This method returns the provided value unchanged.
 777  
      * This can prevent javac from inlining a constant
 778  
      * field, e.g.,
 779  
      *
 780  
      * <pre>
 781  
      *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
 782  
      * </pre>
 783  
      *
 784  
      * This way any jars that refer to this field do not
 785  
      * have to recompile themselves if the field's value
 786  
      * changes at some future date.
 787  
      *
 788  
      * @param v the long value to return
 789  
      * @return the long v, unchanged
 790  
      */
 791  2
     public static long CONST(final long v) { return v; }
 792  
 
 793  
     /**
 794  
      * This method returns the provided value unchanged.
 795  
      * This can prevent javac from inlining a constant
 796  
      * field, e.g.,
 797  
      *
 798  
      * <pre>
 799  
      *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
 800  
      * </pre>
 801  
      *
 802  
      * This way any jars that refer to this field do not
 803  
      * have to recompile themselves if the field's value
 804  
      * changes at some future date.
 805  
      *
 806  
      * @param v the float value to return
 807  
      * @return the float v, unchanged
 808  
      */
 809  2
     public static float CONST(final float v) { return v; }
 810  
 
 811  
     /**
 812  
      * This method returns the provided value unchanged.
 813  
      * This can prevent javac from inlining a constant
 814  
      * field, e.g.,
 815  
      *
 816  
      * <pre>
 817  
      *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
 818  
      * </pre>
 819  
      *
 820  
      * This way any jars that refer to this field do not
 821  
      * have to recompile themselves if the field's value
 822  
      * changes at some future date.
 823  
      *
 824  
      * @param v the double value to return
 825  
      * @return the double v, unchanged
 826  
      */
 827  2
     public static double CONST(final double v) { return v; }
 828  
 
 829  
     /**
 830  
      * This method returns the provided value unchanged.
 831  
      * This can prevent javac from inlining a constant
 832  
      * field, e.g.,
 833  
      *
 834  
      * <pre>
 835  
      *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
 836  
      * </pre>
 837  
      *
 838  
      * This way any jars that refer to this field do not
 839  
      * have to recompile themselves if the field's value
 840  
      * changes at some future date.
 841  
      *
 842  
      * @param <T> the Object type 
 843  
      * @param v the genericized Object value to return (typically a String).
 844  
      * @return the genericized Object v, unchanged (typically a String).
 845  
      */
 846  2
     public static <T> T CONST(final T v) { return v; }
 847  
 
 848  
 }