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