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