    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.time.Duration;
    025import java.util.ArrayList;
    026import java.util.Collection;
    027import java.util.Collections;
    028import java.util.Comparator;
    029import java.util.HashMap;
    030import java.util.Hashtable;
    031import java.util.Map;
    032import java.util.Objects;
    033import java.util.Optional;
    034import java.util.TreeSet;
    035import java.util.function.Supplier;
    036import java.util.stream.Stream;
    037
    038import org.apache.commons.lang3.exception.CloneFailedException;
    039import org.apache.commons.lang3.function.Suppliers;
    040import org.apache.commons.lang3.mutable.MutableInt;
    041import org.apache.commons.lang3.text.StrBuilder;
    042import org.apache.commons.lang3.time.DurationUtils;
    043import org.apache.commons.lang3.stream.Streams;
    044
    045/**
    046 * Operations on {@link Object}.
    047 *
    048 * <p>This class tries to handle {@code null} input gracefully.
    049 * An exception will generally not be thrown for a {@code null} input.
    050 * Each method documents its behavior in more detail.</p>
    051 *
    052 * <p>#ThreadSafe#</p>
    053 * @since 1.0
    054 */
    055//@Immutable
    056@SuppressWarnings("deprecation") // deprecated class StrBuilder is imported
    057// because it is part of the signature of deprecated methods
    058public class ObjectUtils {
    059
    060    /**
    061     * Class used as a null placeholder where {@code null}
    062     * has another meaning.
    063     *
    064     * <p>For example, in a {@link HashMap} the
    065     * {@link java.util.HashMap#get(Object)} method returns
    066     * {@code null} if the {@link Map} contains {@code null} or if there is
    067     * no matching key. The {@code null} placeholder can be used to distinguish
    068     * between these two cases.</p>
    069     *
    070     * <p>Another example is {@link Hashtable}, where {@code null}
    071     * cannot be stored.</p>
    072     */
    073    public static class Null implements Serializable {
    074        /**
    075         * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0
    076         *
    077         * @see java.io.Serializable
    078         */
    079        private static final long serialVersionUID = 7092611880189329093L;
    080
    081        /**
    082         * Restricted constructor - singleton.
    083         */
    084        Null() {
    085        }
    086
    087        /**
    088         * Ensure Singleton after serialization.
    089         *
    090         * @return the singleton value
    091         */
    092        private Object readResolve() {
    093            return NULL;
    094        }
    095    }
    096
    097    private static final char AT_SIGN = '@';
    098
    099    /**
    100     * Singleton used as a {@code null} placeholder where
    101     * {@code null} has another meaning.
    102     *
    103     * <p>For example, in a {@link HashMap} the
    104     * {@link java.util.HashMap#get(Object)} method returns
    105     * {@code null} if the {@link Map} contains {@code null} or if there
    106     * is no matching key. The {@code null} placeholder can be used to
    107     * distinguish between these two cases.</p>
    108     *
    109     * <p>Another example is {@link Hashtable}, where {@code null}
    110     * cannot be stored.</p>
    111     *
    112     * <p>This instance is Serializable.</p>
    113     */
    114    public static final Null NULL = new Null();
    115
    116    /**
    117     * Checks if all values in the array are not {@code nulls}.
    118     *
    119     * <p>
    120     * If any value is {@code null} or the array is {@code null} then
    121     * {@code false} is returned. If all elements in array are not
    122     * {@code null} or the array is empty (contains no elements) {@code true}
    123     * is returned.
    124     * </p>
    125     *
    126     * <pre>
    127     * ObjectUtils.allNotNull(*)             = true
    128     * ObjectUtils.allNotNull(*, *)          = true
    129     * ObjectUtils.allNotNull(null)          = false
    130     * ObjectUtils.allNotNull(null, null)    = false
    131     * ObjectUtils.allNotNull(null, *)       = false
    132     * ObjectUtils.allNotNull(*, null)       = false
    133     * ObjectUtils.allNotNull(*, *, null, *) = false
    134     * </pre>
    135     *
    136     * @param values  the values to test, may be {@code null} or empty
    137     * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null},
    138     * {@code true} if all values in the array are not {@code null}s or array contains no elements.
    139     * @since 3.5
    140     */
    141    public static boolean allNotNull(final Object... values) {
    142        return values != null && Stream.of(values).noneMatch(Objects::isNull);
    143    }
    144
    145    /**
    146     * Checks if all values in the given array are {@code null}.
    147     *
    148     * <p>
    149     * If all the values are {@code null} or the array is {@code null}
    150     * or empty, then {@code true} is returned, otherwise {@code false} is returned.
    151     * </p>
    152     *
    153     * <pre>
    154     * ObjectUtils.allNull(*)                = false
    155     * ObjectUtils.allNull(*, null)          = false
    156     * ObjectUtils.allNull(null, *)          = false
    157     * ObjectUtils.allNull(null, null, *, *) = false
    158     * ObjectUtils.allNull(null)             = true
    159     * ObjectUtils.allNull(null, null)       = true
    160     * </pre>
    161     *
    162     * @param values  the values to test, may be {@code null} or empty
    163     * @return {@code true} if all values in the array are {@code null}s,
    164     * {@code false} if there is at least one non-null value in the array.
    165     * @since 3.11
    166     */
    167    public static boolean allNull(final Object... values) {
    168        return !anyNotNull(values);
    169    }
    170
    171    /**
    172     * Checks if any value in the given array is not {@code null}.
    173     *
    174     * <p>
    175     * If all the values are {@code null} or the array is {@code null}
    176     * or empty then {@code false} is returned. Otherwise {@code true} is returned.
    177     * </p>
    178     *
    179     * <pre>
    180     * ObjectUtils.anyNotNull(*)                = true
    181     * ObjectUtils.anyNotNull(*, null)          = true
    182     * ObjectUtils.anyNotNull(null, *)          = true
    183     * ObjectUtils.anyNotNull(null, null, *, *) = true
    184     * ObjectUtils.anyNotNull(null)             = false
    185     * ObjectUtils.anyNotNull(null, null)       = false
    186     * </pre>
    187     *
    188     * @param values  the values to test, may be {@code null} or empty
    189     * @return {@code true} if there is at least one non-null value in the array,
    190     * {@code false} if all values in the array are {@code null}s.
    191     * If the array is {@code null} or empty {@code false} is also returned.
    192     * @since 3.5
    193     */
    194    public static boolean anyNotNull(final Object... values) {
    195        return firstNonNull(values) != null;
    196    }
    197
    198    /**
    199     * Checks if any value in the given array is {@code null}.
    200     *
    201     * <p>
    202     * If any of the values are {@code null} or the array is {@code null},
    203     * then {@code true} is returned, otherwise {@code false} is returned.
    204     * </p>
    205     *
    206     * <pre>
    207     * ObjectUtils.anyNull(*)             = false
    208     * ObjectUtils.anyNull(*, *)          = false
    209     * ObjectUtils.anyNull(null)          = true
    210     * ObjectUtils.anyNull(null, null)    = true
    211     * ObjectUtils.anyNull(null, *)       = true
    212     * ObjectUtils.anyNull(*, null)       = true
    213     * ObjectUtils.anyNull(*, *, null, *) = true
    214     * </pre>
    215     *
    216     * @param values  the values to test, may be {@code null} or empty
    217     * @return {@code true} if there is at least one {@code null} value in the array,
    218     * {@code false} if all the values are non-null.
    219     * If the array is {@code null} or empty, {@code true} is also returned.
    220     * @since 3.11
    221     */
    222    public static boolean anyNull(final Object... values) {
    223        return !allNotNull(values);
    224    }
    225
    226    /**
    227     * Clone an object.
    228     *
    229     * @param <T> the type of the object
    230     * @param obj  the object to clone, null returns null
    231     * @return the clone if the object implements {@link Cloneable} otherwise {@code null}
    232     * @throws CloneFailedException if the object is cloneable and the clone operation fails
    233     * @since 3.0
    234     */
    235    public static <T> T clone(final T obj) {
    236        if (obj instanceof Cloneable) {
    237            final Object result;
    238            if (isArray(obj)) {
    239                final Class<?> componentType = obj.getClass().getComponentType();
    240                if (componentType.isPrimitive()) {
    241                    int length = Array.getLength(obj);
    242                    result = Array.newInstance(componentType, length);
    243                    while (length-- > 0) {
    244                        Array.set(result, length, Array.get(obj, length));
    245                    }
    246                } else {
    247                    result = ((Object[]) obj).clone();
    248                }
    249            } else {
    250                try {
    251                    final Method clone = obj.getClass().getMethod("clone");
    252                    result = clone.invoke(obj);
    253                } catch (final NoSuchMethodException e) {
    254                    throw new CloneFailedException("Cloneable type "
    255                        + obj.getClass().getName()
    256                        + " has no clone method", e);
    257                } catch (final IllegalAccessException e) {
    258                    throw new CloneFailedException("Cannot clone Cloneable type "
    259                        + obj.getClass().getName(), e);
    260                } catch (final InvocationTargetException e) {
    261                    throw new CloneFailedException("Exception cloning Cloneable type "
    262                        + obj.getClass().getName(), e.getCause());
    263                }
    264            }
    265            @SuppressWarnings("unchecked") // OK because input is of type T
    266            final T checked = (T) result;
    267            return checked;
    268        }
    269
    270        return null;
    271    }
    272
    273    /**
    274     * Clone an object if possible.
    275     *
    276     * <p>This method is similar to {@link #clone(Object)}, but will return the provided
    277     * instance as the return value instead of {@code null} if the instance
    278     * is not cloneable. This is more convenient if the caller uses different
    279     * implementations (e.g. of a service) and some of the implementations do not allow concurrent
    280     * processing or have state. In such cases the implementation can simply provide a proper
    281     * clone implementation and the caller's code does not have to change.</p>
    282     *
    283     * @param <T> the type of the object
    284     * @param obj  the object to clone, null returns null
    285     * @return the clone if the object implements {@link Cloneable} otherwise the object itself
    286     * @throws CloneFailedException if the object is cloneable and the clone operation fails
    287     * @since 3.0
    288     */
    289    public static <T> T cloneIfPossible(final T obj) {
    290        final T clone = clone(obj);
    291        return clone == null ? obj : clone;
    292    }
    293
    294    /**
    295     * Null safe comparison of Comparables.
    296     * {@code null} is assumed to be less than a non-{@code null} value.
    297     * <p>TODO Move to ComparableUtils.</p>
    298     *
    299     * @param <T> type of the values processed by this method
    300     * @param c1  the first comparable, may be null
    301     * @param c2  the second comparable, may be null
    302     * @return a negative value if c1 &lt; c2, zero if c1 = c2
    303     *  and a positive value if c1 &gt; c2
    304     */
    305    public static <T extends Comparable<? super T>> int compare(final T c1, final T c2) {
    306        return compare(c1, c2, false);
    307    }
    308
    309    /**
    310     * Null safe comparison of Comparables.
    311     * <p>TODO Move to ComparableUtils.</p>
    312     *
    313     * @param <T> type of the values processed by this method
    314     * @param c1  the first comparable, may be null
    315     * @param c2  the second comparable, may be null
    316     * @param nullGreater if true {@code null} is considered greater
    317     *  than a non-{@code null} value or if false {@code null} is
    318     *  considered less than a Non-{@code null} value
    319     * @return a negative value if c1 &lt; c2, zero if c1 = c2
    320     *  and a positive value if c1 &gt; c2
    321     * @see java.util.Comparator#compare(Object, Object)
    322     */
    323    public static <T extends Comparable<? super T>> int compare(final T c1, final T c2, final boolean nullGreater) {
    324        if (c1 == c2) {
    325            return 0;
    326        }
    327        if (c1 == null) {
    328            return nullGreater ? 1 : -1;
    329        }
    330        if (c2 == null) {
    331            return nullGreater ? -1 : 1;
    332        }
    333        return c1.compareTo(c2);
    334    }
    335
    336    /**
    337     * This method returns the provided value unchanged.
    338     * This can prevent javac from inlining a constant
    339     * field, e.g.,
    340     *
    341     * <pre>
    342     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
    343     * </pre>
    344     *
    345     * This way any jars that refer to this field do not
    346     * have to recompile themselves if the field's value
    347     * changes at some future date.
    348     *
    349     * @param v the boolean value to return
    350     * @return the boolean v, unchanged
    351     * @since 3.2
    352     */
    353    public static boolean CONST(final boolean v) {
    354        return v;
    355    }
    356
    357    /**
    358     * This method returns the provided value unchanged.
    359     * This can prevent javac from inlining a constant
    360     * field, e.g.,
    361     *
    362     * <pre>
    363     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
    364     * </pre>
    365     *
    366     * This way any jars that refer to this field do not
    367     * have to recompile themselves if the field's value
    368     * changes at some future date.
    369     *
    370     * @param v the byte value to return
    371     * @return the byte v, unchanged
    372     * @since 3.2
    373     */
    374    public static byte CONST(final byte v) {
    375        return v;
    376    }
    377
    378    /**
    379     * This method returns the provided value unchanged.
    380     * This can prevent javac from inlining a constant
    381     * field, e.g.,
    382     *
    383     * <pre>
    384     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
    385     * </pre>
    386     *
    387     * This way any jars that refer to this field do not
    388     * have to recompile themselves if the field's value
    389     * changes at some future date.
    390     *
    391     * @param v the char value to return
    392     * @return the char v, unchanged
    393     * @since 3.2
    394     */
    395    public static char CONST(final char v) {
    396        return v;
    397    }
    398
    399    /**
    400     * This method returns the provided value unchanged.
    401     * This can prevent javac from inlining a constant
    402     * field, e.g.,
    403     *
    404     * <pre>
    405     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
    406     * </pre>
    407     *
    408     * This way any jars that refer to this field do not
    409     * have to recompile themselves if the field's value
    410     * changes at some future date.
    411     *
    412     * @param v the double value to return
    413     * @return the double v, unchanged
    414     * @since 3.2
    415     */
    416    public static double CONST(final double v) {
    417        return v;
    418    }
    419
    420    /**
    421     * This method returns the provided value unchanged.
    422     * This can prevent javac from inlining a constant
    423     * field, e.g.,
    424     *
    425     * <pre>
    426     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
    427     * </pre>
    428     *
    429     * This way any jars that refer to this field do not
    430     * have to recompile themselves if the field's value
    431     * changes at some future date.
    432     *
    433     * @param v the float value to return
    434     * @return the float v, unchanged
    435     * @since 3.2
    436     */
    437    public static float CONST(final float v) {
    438        return v;
    439    }
    440
    441    /**
    442     * This method returns the provided value unchanged.
    443     * This can prevent javac from inlining a constant
    444     * field, e.g.,
    445     *
    446     * <pre>
    447     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
    448     * </pre>
    449     *
    450     * This way any jars that refer to this field do not
    451     * have to recompile themselves if the field's value
    452     * changes at some future date.
    453     *
    454     * @param v the int value to return
    455     * @return the int v, unchanged
    456     * @since 3.2
    457     */
    458    public static int CONST(final int v) {
    459        return v;
    460    }
    461
    462    /**
    463     * This method returns the provided value unchanged.
    464     * This can prevent javac from inlining a constant
    465     * field, e.g.,
    466     *
    467     * <pre>
    468     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
    469     * </pre>
    470     *
    471     * This way any jars that refer to this field do not
    472     * have to recompile themselves if the field's value
    473     * changes at some future date.
    474     *
    475     * @param v the long value to return
    476     * @return the long v, unchanged
    477     * @since 3.2
    478     */
    479    public static long CONST(final long v) {
    480        return v;
    481    }
    482
    483    /**
    484     * This method returns the provided value unchanged.
    485     * This can prevent javac from inlining a constant
    486     * field, e.g.,
    487     *
    488     * <pre>
    489     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
    490     * </pre>
    491     *
    492     * This way any jars that refer to this field do not
    493     * have to recompile themselves if the field's value
    494     * changes at some future date.
    495     *
    496     * @param v the short value to return
    497     * @return the short v, unchanged
    498     * @since 3.2
    499     */
    500    public static short CONST(final short v) {
    501        return v;
    502    }
    503
    504    /**
    505     * This method returns the provided value unchanged.
    506     * This can prevent javac from inlining a constant
    507     * field, e.g.,
    508     *
    509     * <pre>
    510     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
    511     * </pre>
    512     *
    513     * This way any jars that refer to this field do not
    514     * have to recompile themselves if the field's value
    515     * changes at some future date.
    516     *
    517     * @param <T> the Object type
    518     * @param v the genericized Object value to return (typically a String).
    519     * @return the genericized Object v, unchanged (typically a String).
    520     * @since 3.2
    521     */
    522    public static <T> T CONST(final T v) {
    523        return v;
    524    }
    525
    526    /**
    527     * This method returns the provided value unchanged.
    528     * This can prevent javac from inlining a constant
    529     * field, e.g.,
    530     *
    531     * <pre>
    532     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
    533     * </pre>
    534     *
    535     * This way any jars that refer to this field do not
    536     * have to recompile themselves if the field's value
    537     * changes at some future date.
    538     *
    539     * @param v the byte literal (as an int) value to return
    540     * @throws IllegalArgumentException if the value passed to v
    541     *         is larger than a byte, that is, smaller than -128 or
    542     *         larger than 127.
    543     * @return the byte v, unchanged
    544     * @since 3.2
    545     */
    546    public static byte CONST_BYTE(final int v) {
    547        if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) {
    548            throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]");
    549        }
    550        return (byte) v;
    551    }
    552
    553    /**
    554     * This method returns the provided value unchanged.
    555     * This can prevent javac from inlining a constant
    556     * field, e.g.,
    557     *
    558     * <pre>
    559     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
    560     * </pre>
    561     *
    562     * This way any jars that refer to this field do not
    563     * have to recompile themselves if the field's value
    564     * changes at some future date.
    565     *
    566     * @param v the short literal (as an int) value to return
    567     * @throws IllegalArgumentException if the value passed to v
    568     *         is larger than a short, that is, smaller than -32768 or
    569     *         larger than 32767.
    570     * @return the byte v, unchanged
    571     * @since 3.2
    572     */
    573    public static short CONST_SHORT(final int v) {
    574        if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) {
    575            throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]");
    576        }
    577        return (short) v;
    578    }
    579
    580    /**
    581     * Returns a default value if the object passed is {@code null}.
    582     *
    583     * <pre>
    584     * ObjectUtils.defaultIfNull(null, null)      = null
    585     * ObjectUtils.defaultIfNull(null, "")        = ""
    586     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
    587     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
    588     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
    589     * </pre>
    590     *
    591     * @param <T> the type of the object
    592     * @param object  the {@link Object} to test, may be {@code null}
    593     * @param defaultValue  the default value to return, may be {@code null}
    594     * @return {@code object} if it is not {@code null}, defaultValue otherwise
    595     * TODO Rename to getIfNull in 4.0
    596     */
    597    public static <T> T defaultIfNull(final T object, final T defaultValue) {
    598        return object != null ? object : defaultValue;
    599    }
    600
    601    // Null-safe equals/hashCode
    602    /**
    603     * Compares two objects for equality, where either one or both
    604     * objects may be {@code null}.
    605     *
    606     * <pre>
    607     * ObjectUtils.equals(null, null)                  = true
    608     * ObjectUtils.equals(null, "")                    = false
    609     * ObjectUtils.equals("", null)                    = false
    610     * ObjectUtils.equals("", "")                      = true
    611     * ObjectUtils.equals(Boolean.TRUE, null)          = false
    612     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
    613     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
    614     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
    615     * </pre>
    616     *
    617     * @param object1  the first object, may be {@code null}
    618     * @param object2  the second object, may be {@code null}
    619     * @return {@code true} if the values of both objects are the same
    620     * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will
    621     * be removed from future releases.
    622     */
    623    @Deprecated
    624    public static boolean equals(final Object object1, final Object object2) {
    625        return Objects.equals(object1, object2);
    626    }
    627
    628    /**
    629     * Returns the first value in the array which is not {@code null}.
    630     * If all the values are {@code null} or the array is {@code null}
    631     * or empty then {@code null} is returned.
    632     *
    633     * <pre>
    634     * ObjectUtils.firstNonNull(null, null)      = null
    635     * ObjectUtils.firstNonNull(null, "")        = ""
    636     * ObjectUtils.firstNonNull(null, null, "")  = ""
    637     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
    638     * ObjectUtils.firstNonNull("abc", *)        = "abc"
    639     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
    640     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
    641     * ObjectUtils.firstNonNull()                = null
    642     * </pre>
    643     *
    644     * @param <T> the component type of the array
    645     * @param values  the values to test, may be {@code null} or empty
    646     * @return the first value from {@code values} which is not {@code null},
    647     *  or {@code null} if there are no non-null values
    648     * @since 3.0
    649     */
    650    @SafeVarargs
    651    public static <T> T firstNonNull(final T... values) {
    652        return Streams.of(values).filter(Objects::nonNull).findFirst().orElse(null);
    653    }
    654
    655    /**
    656     * Delegates to {@link Object#getClass()} using generics.
    657     *
    658     * @param <T> The argument type or null.
    659     * @param object The argument.
    660     * @return The argument's Class or null.
    661     * @since 3.13.0
    662     */
    663    @SuppressWarnings("unchecked")
    664    public static <T> Class<T> getClass(final T object) {
    665        return object == null ? null : (Class<T>) object.getClass();
    666    }
    667
    668    /**
    669     * Executes the given suppliers in order and returns the first return
    670     * value where a value other than {@code null} is returned.
    671     * Once a non-{@code null} value is obtained, all following suppliers are
    672     * not executed anymore.
    673     * If all the return values are {@code null} or no suppliers are provided
    674     * then {@code null} is returned.
    675     *
    676     * <pre>
    677     * ObjectUtils.firstNonNullLazy(null, () -&gt; null) = null
    678     * ObjectUtils.firstNonNullLazy(() -&gt; null, () -&gt; "") = ""
    679     * ObjectUtils.firstNonNullLazy(() -&gt; "", () -&gt; throw new IllegalStateException()) = ""
    680     * ObjectUtils.firstNonNullLazy(() -&gt; null, () -&gt; "zz) = "zz"
    681     * ObjectUtils.firstNonNullLazy() = null
    682     * </pre>
    683     *
    684     * @param <T> the type of the return values
    685     * @param suppliers  the suppliers returning the values to test.
    686     *                   {@code null} values are ignored.
    687     *                   Suppliers may return {@code null} or a value of type @{code T}
    688     * @return the first return value from {@code suppliers} which is not {@code null},
    689     *  or {@code null} if there are no non-null values
    690     * @since 3.10
    691     */
    692    @SafeVarargs
    693    public static <T> T getFirstNonNull(final Supplier<T>... suppliers) {
    694        return Streams.of(suppliers).map(s -> s != null ? s.get() : null).filter(Objects::nonNull).findFirst().orElse(null);
    695    }
    696
    697    /**
    698     * Returns the given {@code object} is it is non-null, otherwise returns the Supplier's {@link Supplier#get()}
    699     * value.
    700     *
    701     * <p>
    702     * The caller responsible for thread-safety and exception handling of default value supplier.
    703     * </p>
    704     *
    705     * <pre>
    706     * ObjectUtils.getIfNull(null, () -&gt; null)     = null
    707     * ObjectUtils.getIfNull(null, null)              = null
    708     * ObjectUtils.getIfNull(null, () -&gt; "")       = ""
    709     * ObjectUtils.getIfNull(null, () -&gt; "zz")     = "zz"
    710     * ObjectUtils.getIfNull("abc", *)                = "abc"
    711     * ObjectUtils.getIfNull(Boolean.TRUE, *)         = Boolean.TRUE
    712     * </pre>
    713     *
    714     * @param <T> the type of the object
    715     * @param object the {@link Object} to test, may be {@code null}
    716     * @param defaultSupplier the default value to return, may be {@code null}
    717     * @return {@code object} if it is not {@code null}, {@code defaultValueSupplier.get()} otherwise
    718     * @since 3.10
    719     */
    720    public static <T> T getIfNull(final T object, final Supplier<T> defaultSupplier) {
    721        return object != null ? object : Suppliers.get(defaultSupplier);
    722    }
    723
    724    /**
    725     * Gets the hash code of an object returning zero when the
    726     * object is {@code null}.
    727     *
    728     * <pre>
    729     * ObjectUtils.hashCode(null)   = 0
    730     * ObjectUtils.hashCode(obj)    = obj.hashCode()
    731     * </pre>
    732     *
    733     * @param obj  the object to obtain the hash code of, may be {@code null}
    734     * @return the hash code of the object, or zero if null
    735     * @since 2.1
    736     * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be
    737     * removed in future releases
    738     */
    739    @Deprecated
    740    public static int hashCode(final Object obj) {
    741        // hashCode(Object) for performance vs. hashCodeMulti(Object[]), as hash code is often critical
    742        return Objects.hashCode(obj);
    743    }
    744
    745    /**
    746     * Returns the hex hash code for the given object per {@link Objects#hashCode(Object)}.
    747     * <p>
    748     * Short hand for {@code Integer.toHexString(Objects.hashCode(object))}.
    749     * </p>
    750     *
    751     * @param object object for which the hashCode is to be calculated
    752     * @return Hash code in hexadecimal format.
    753     * @since 3.13.0
    754     */
    755    public static String hashCodeHex(final Object object) {
    756        return Integer.toHexString(Objects.hashCode(object));
    757    }
    758
    759
    760    /**
    761     * Gets the hash code for multiple objects.
    762     *
    763     * <p>This allows a hash code to be rapidly calculated for a number of objects.
    764     * The hash code for a single object is the <em>not</em> same as {@link #hashCode(Object)}.
    765     * The hash code for multiple objects is the same as that calculated by an
    766     * {@link ArrayList} containing the specified objects.</p>
    767     *
    768     * <pre>
    769     * ObjectUtils.hashCodeMulti()                 = 1
    770     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
    771     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
    772     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
    773     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
    774     * </pre>
    775     *
    776     * @param objects  the objects to obtain the hash code of, may be {@code null}
    777     * @return the hash code of the objects, or zero if null
    778     * @since 3.0
    779     * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be
    780     * removed in future releases.
    781     */
    782    @Deprecated
    783    public static int hashCodeMulti(final Object... objects) {
    784        int hash = 1;
    785        if (objects != null) {
    786            for (final Object object : objects) {
    787                final int tmpHash = Objects.hashCode(object);
    788                hash = hash * 31 + tmpHash;
    789            }
    790        }
    791        return hash;
    792    }
    793
    794    /**
    795     * Returns the hex hash code for the given object per {@link System#identityHashCode(Object)}.
    796     * <p>
    797     * Short hand for {@code Integer.toHexString(System.identityHashCode(object))}.
    798     * </p>
    799     *
    800     * @param object object for which the hashCode is to be calculated
    801     * @return Hash code in hexadecimal format.
    802     * @since 3.13.0
    803     */
    804    public static String identityHashCodeHex(final Object object) {
    805        return Integer.toHexString(System.identityHashCode(object));
    806    }
    807
    808    /**
    809     * Appends the toString that would be produced by {@link Object}
    810     * if a class did not override toString itself. {@code null}
    811     * will throw a NullPointerException for either of the two parameters.
    812     *
    813     * <pre>
    814     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23")
    815     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
    816     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
    817     * </pre>
    818     *
    819     * @param appendable  the appendable to append to
    820     * @param object  the object to create a toString for
    821     * @throws IOException if an I/O error occurs.
    822     * @since 3.2
    823     */
    824    public static void identityToString(final Appendable appendable, final Object object) throws IOException {
    825        Objects.requireNonNull(object, "object");
    826        appendable.append(object.getClass().getName())
    827              .append(AT_SIGN)
    828              .append(identityHashCodeHex(object));
    829    }
    830
    831    /**
    832     * Gets the toString that would be produced by {@link Object}
    833     * if a class did not override toString itself. {@code null}
    834     * will return {@code null}.
    835     *
    836     * <pre>
    837     * ObjectUtils.identityToString(null)         = null
    838     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
    839     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
    840     * </pre>
    841     *
    842     * @param object  the object to create a toString for, may be
    843     *  {@code null}
    844     * @return the default toString text, or {@code null} if
    845     *  {@code null} passed in
    846     */
    847    public static String identityToString(final Object object) {
    848        if (object == null) {
    849            return null;
    850        }
    851        final String name = object.getClass().getName();
    852        final String hexString = identityHashCodeHex(object);
    853        final StringBuilder builder = new StringBuilder(name.length() + 1 + hexString.length());
    854        // @formatter:off
    855        builder.append(name)
    856              .append(AT_SIGN)
    857              .append(hexString);
    858        // @formatter:on
    859        return builder.toString();
    860    }
    861
    862    /**
    863     * Appends the toString that would be produced by {@link Object}
    864     * if a class did not override toString itself. {@code null}
    865     * will throw a NullPointerException for either of the two parameters.
    866     *
    867     * <pre>
    868     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23")
    869     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
    870     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
    871     * </pre>
    872     *
    873     * @param builder  the builder to append to
    874     * @param object  the object to create a toString for
    875     * @since 3.2
    876     * @deprecated as of 3.6, because StrBuilder was moved to commons-text,
    877     *  use one of the other {@code identityToString} methods instead
    878     */
    879    @Deprecated
    880    public static void identityToString(final StrBuilder builder, final Object object) {
    881        Objects.requireNonNull(object, "object");
    882        final String name = object.getClass().getName();
    883        final String hexString = identityHashCodeHex(object);
    884        builder.ensureCapacity(builder.length() +  name.length() + 1 + hexString.length());
    885        builder.append(name)
    886              .append(AT_SIGN)
    887              .append(hexString);
    888    }
    889
    890    /**
    891     * Appends the toString that would be produced by {@link Object}
    892     * if a class did not override toString itself. {@code null}
    893     * will throw a NullPointerException for either of the two parameters.
    894     *
    895     * <pre>
    896     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23")
    897     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
    898     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
    899     * </pre>
    900     *
    901     * @param buffer  the buffer to append to
    902     * @param object  the object to create a toString for
    903     * @since 2.4
    904     */
    905    public static void identityToString(final StringBuffer buffer, final Object object) {
    906        Objects.requireNonNull(object, "object");
    907        final String name = object.getClass().getName();
    908        final String hexString = identityHashCodeHex(object);
    909        buffer.ensureCapacity(buffer.length() + name.length() + 1 + hexString.length());
    910        buffer.append(name)
    911              .append(AT_SIGN)
    912              .append(hexString);
    913    }
    914
    915    /**
    916     * Appends the toString that would be produced by {@link Object}
    917     * if a class did not override toString itself. {@code null}
    918     * will throw a NullPointerException for either of the two parameters.
    919     *
    920     * <pre>
    921     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23")
    922     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
    923     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
    924     * </pre>
    925     *
    926     * @param builder  the builder to append to
    927     * @param object  the object to create a toString for
    928     * @since 3.2
    929     */
    930    public static void identityToString(final StringBuilder builder, final Object object) {
    931        Objects.requireNonNull(object, "object");
    932        final String name = object.getClass().getName();
    933        final String hexString = identityHashCodeHex(object);
    934        builder.ensureCapacity(builder.length() +  name.length() + 1 + hexString.length());
    935        builder.append(name)
    936              .append(AT_SIGN)
    937              .append(hexString);
    938    }
    939
    940
    941    // Constants (LANG-816):
    942    /*
    943        These methods ensure constants are not inlined by javac.
    944        For example, typically a developer might declare a constant like so:
    945
    946            public final static int MAGIC_NUMBER = 5;
    947
    948        Should a different jar file refer to this, and the MAGIC_NUMBER
    949        is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar
    950        file will need to recompile itself.  This is because javac
    951        typically inlines the primitive or String constant directly into
    952        the bytecode, and removes the reference to the MAGIC_NUMBER field.
    953
    954        To help the other jar (so that it does not need to recompile
    955        when constants are changed) the original developer can declare
    956        their constant using one of the CONST() utility methods, instead:
    957
    958            public final static int MAGIC_NUMBER = CONST(5);
    959     */
    960
    961    /**
    962     * Tests whether the given object is an Object array or a primitive array in a null-safe manner.
    963     *
    964     * <p>
    965     * A {@code null} {@code object} Object will return {@code false}.
    966     * </p>
    967     *
    968     * <pre>
    969     * ObjectUtils.isArray(null)             = false
    970     * ObjectUtils.isArray("")               = false
    971     * ObjectUtils.isArray("ab")             = false
    972     * ObjectUtils.isArray(new int[]{})      = true
    973     * ObjectUtils.isArray(new int[]{1,2,3}) = true
    974     * ObjectUtils.isArray(1234)             = false
    975     * </pre>
    976     *
    977     * @param object the object to check, may be {@code null}
    978     * @return {@code true} if the object is an {@code array}, {@code false} otherwise
    979     * @since 3.13.0
    980     */
    981    public static boolean isArray(final Object object) {
    982        return object != null && object.getClass().isArray();
    983    }
    984
    985    /**
    986     * Tests if an Object is empty or null.
    987     *
    988     * The following types are supported:
    989     * <ul>
    990     * <li>{@link CharSequence}: Considered empty if its length is zero.</li>
    991     * <li>{@link Array}: Considered empty if its length is zero.</li>
    992     * <li>{@link Collection}: Considered empty if it has zero elements.</li>
    993     * <li>{@link Map}: Considered empty if it has zero key-value mappings.</li>
    994     * <li>{@link Optional}: Considered empty if {@link Optional#isPresent} returns false, regardless of the "emptiness" of the contents.</li>
    995     * </ul>
    996     *
    997     * <pre>
    998     * ObjectUtils.isEmpty(null)             = true
    999     * ObjectUtils.isEmpty("")               = true
    1000     * ObjectUtils.isEmpty("ab")             = false
    1001     * ObjectUtils.isEmpty(new int[]{})      = true
    1002     * ObjectUtils.isEmpty(new int[]{1,2,3}) = false
    1003     * ObjectUtils.isEmpty(1234)             = false
    1004     * ObjectUtils.isEmpty(1234)             = false
    1005     * ObjectUtils.isEmpty(Optional.of(""))  = false
    1006     * ObjectUtils.isEmpty(Optional.empty()) = true
    1007     * </pre>
    1008     *
    1009     * @param object  the {@link Object} to test, may be {@code null}
    1010     * @return {@code true} if the object has a supported type and is empty or null,
    1011     * {@code false} otherwise
    1012     * @since 3.9
    1013     */
    1014    public static boolean isEmpty(final Object object) {
    1015        if (object == null) {
    1016            return true;
    1017        }
    1018        if (object instanceof CharSequence) {
    1019            return ((CharSequence) object).length() == 0;
    1020        }
    1021        if (isArray(object)) {
    1022            return Array.getLength(object) == 0;
    1023        }
    1024        if (object instanceof Collection<?>) {
    1025            return ((Collection<?>) object).isEmpty();
    1026        }
    1027        if (object instanceof Map<?, ?>) {
    1028            return ((Map<?, ?>) object).isEmpty();
    1029        }
    1030        if (object instanceof Optional<?>) {
    1031            // TODO Java 11 Use Optional#isEmpty()
    1032            return !((Optional<?>) object).isPresent();
    1033        }
    1034        return false;
    1035    }
    1036
    1037    /**
    1038     * Tests if an Object is not empty and not null.
    1039     *
    1040     * The following types are supported:
    1041     * <ul>
    1042     * <li>{@link CharSequence}: Considered empty if its length is zero.</li>
    1043     * <li>{@link Array}: Considered empty if its length is zero.</li>
    1044     * <li>{@link Collection}: Considered empty if it has zero elements.</li>
    1045     * <li>{@link Map}: Considered empty if it has zero key-value mappings.</li>
    1046     * <li>{@link Optional}: Considered empty if {@link Optional#isPresent} returns false, regardless of the "emptiness" of the contents.</li>
    1047     * </ul>
    1048     *
    1049     * <pre>
    1050     * ObjectUtils.isNotEmpty(null)             = false
    1051     * ObjectUtils.isNotEmpty("")               = false
    1052     * ObjectUtils.isNotEmpty("ab")             = true
    1053     * ObjectUtils.isNotEmpty(new int[]{})      = false
    1054     * ObjectUtils.isNotEmpty(new int[]{1,2,3}) = true
    1055     * ObjectUtils.isNotEmpty(1234)             = true
    1056     * ObjectUtils.isNotEmpty(Optional.of(""))  = true
    1057     * ObjectUtils.isNotEmpty(Optional.empty()) = false
    1058     * </pre>
    1059     *
    1060     * @param object  the {@link Object} to test, may be {@code null}
    1061     * @return {@code true} if the object has an unsupported type or is not empty
    1062     * and not null, {@code false} otherwise
    1063     * @since 3.9
    1064     */
    1065    public static boolean isNotEmpty(final Object object) {
    1066        return !isEmpty(object);
    1067    }
    1068
    1069    /**
    1070     * Null safe comparison of Comparables.
    1071     * <p>TODO Move to ComparableUtils.</p>
    1072     *
    1073     * @param <T> type of the values processed by this method
    1074     * @param values the set of comparable values, may be null
    1075     * @return
    1076     *  <ul>
    1077     *   <li>If any objects are non-null and unequal, the greater object.
    1078     *   <li>If all objects are non-null and equal, the first.
    1079     *   <li>If any of the comparables are null, the greater of the non-null objects.
    1080     *   <li>If all the comparables are null, null is returned.
    1081     *  </ul>
    1082     */
    1083    @SafeVarargs
    1084    public static <T extends Comparable<? super T>> T max(final T... values) {
    1085        T result = null;
    1086        if (values != null) {
    1087            for (final T value : values) {
    1088                if (compare(value, result, false) > 0) {
    1089                    result = value;
    1090                }
    1091            }
    1092        }
    1093        return result;
    1094    }
    1095
    1096    /**
    1097     * Find the "best guess" middle value among comparables. If there is an even
    1098     * number of total values, the lower of the two middle values will be returned.
    1099     * @param <T> type of values processed by this method
    1100     * @param comparator to use for comparisons
    1101     * @param items to compare
    1102     * @return T at middle position
    1103     * @throws NullPointerException if items or comparator is {@code null}
    1104     * @throws IllegalArgumentException if items is empty or contains {@code null} values
    1105     * @since 3.0.1
    1106     */
    1107    @SafeVarargs
    1108    public static <T> T median(final Comparator<T> comparator, final T... items) {
    1109        Validate.notEmpty(items, "null/empty items");
    1110        Validate.noNullElements(items);
    1111        Objects.requireNonNull(comparator, "comparator");
    1112        final TreeSet<T> treeSet = new TreeSet<>(comparator);
    1113        Collections.addAll(treeSet, items);
    1114        @SuppressWarnings("unchecked") //we know all items added were T instances
    1115        final T result = (T) treeSet.toArray()[(treeSet.size() - 1) / 2];
    1116        return result;
    1117    }
    1118
    1119    /**
    1120     * Find the "best guess" middle value among comparables. If there is an even
    1121     * number of total values, the lower of the two middle values will be returned.
    1122     * @param <T> type of values processed by this method
    1123     * @param items to compare
    1124     * @return T at middle position
    1125     * @throws NullPointerException if items is {@code null}
    1126     * @throws IllegalArgumentException if items is empty or contains {@code null} values
    1127     * @since 3.0.1
    1128     */
    1129    @SafeVarargs
    1130    public static <T extends Comparable<? super T>> T median(final T... items) {
    1131        Validate.notEmpty(items);
    1132        Validate.noNullElements(items);
    1133        final TreeSet<T> sort = new TreeSet<>();
    1134        Collections.addAll(sort, items);
    1135        @SuppressWarnings("unchecked") //we know all items added were T instances
    1136        final T result = (T) sort.toArray()[(sort.size() - 1) / 2];
    1137        return result;
    1138    }
    1139
    1140    /**
    1141     * Null safe comparison of Comparables.
    1142     * <p>TODO Move to ComparableUtils.</p>
    1143     *
    1144     * @param <T> type of the values processed by this method
    1145     * @param values the set of comparable values, may be null
    1146     * @return
    1147     *  <ul>
    1148     *   <li>If any objects are non-null and unequal, the lesser object.
    1149     *   <li>If all objects are non-null and equal, the first.
    1150     *   <li>If any of the comparables are null, the lesser of the non-null objects.
    1151     *   <li>If all the comparables are null, null is returned.
    1152     *  </ul>
    1153     */
    1154    @SafeVarargs
    1155    public static <T extends Comparable<? super T>> T min(final T... values) {
    1156        T result = null;
    1157        if (values != null) {
    1158            for (final T value : values) {
    1159                if (compare(value, result, true) < 0) {
    1160                    result = value;
    1161                }
    1162            }
    1163        }
    1164        return result;
    1165    }
    1166
    1167
    1168    /**
    1169     * Find the most frequently occurring item.
    1170     *
    1171     * @param <T> type of values processed by this method
    1172     * @param items to check
    1173     * @return most populous T, {@code null} if non-unique or no items supplied
    1174     * @since 3.0.1
    1175     */
    1176    @SafeVarargs
    1177    public static <T> T mode(final T... items) {
    1178        if (ArrayUtils.isNotEmpty(items)) {
    1179            final HashMap<T, MutableInt> occurrences = new HashMap<>(items.length);
    1180            for (final T t : items) {
    1181                final MutableInt count = occurrences.get(t);
    1182                if (count == null) {
    1183                    occurrences.put(t, new MutableInt(1));
    1184                } else {
    1185                    count.increment();
    1186                }
    1187            }
    1188            T result = null;
    1189            int max = 0;
    1190            for (final Map.Entry<T, MutableInt> e : occurrences.entrySet()) {
    1191                final int cmp = e.getValue().intValue();
    1192                if (cmp == max) {
    1193                    result = null;
    1194                } else if (cmp > max) {
    1195                    max = cmp;
    1196                    result = e.getKey();
    1197                }
    1198            }
    1199            return result;
    1200        }
    1201        return null;
    1202    }
    1203
    1204    /**
    1205     * Compares two objects for inequality, where either one or both
    1206     * objects may be {@code null}.
    1207     *
    1208     * <pre>
    1209     * ObjectUtils.notEqual(null, null)                  = false
    1210     * ObjectUtils.notEqual(null, "")                    = true
    1211     * ObjectUtils.notEqual("", null)                    = true
    1212     * ObjectUtils.notEqual("", "")                      = false
    1213     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
    1214     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
    1215     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
    1216     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
    1217     * </pre>
    1218     *
    1219     * @param object1  the first object, may be {@code null}
    1220     * @param object2  the second object, may be {@code null}
    1221     * @return {@code false} if the values of both objects are the same
    1222     */
    1223    public static boolean notEqual(final Object object1, final Object object2) {
    1224        return !Objects.equals(object1, object2);
    1225    }
    1226
    1227    /**
    1228     * Checks that the specified object reference is not {@code null} or empty per {@link #isEmpty(Object)}. Use this
    1229     * method for validation, for example:
    1230     *
    1231     * <blockquote>
    1232     *
    1233     * <pre>
    1234     * public Foo(Bar bar) {
    1235     *     this.bar = Objects.requireNonEmpty(bar);
    1236     * }
    1237     * </pre>
    1238     *
    1239     * </blockquote>
    1240     *
    1241     * @param <T> the type of the reference.
    1242     * @param obj the object reference to check for nullity.
    1243     * @return {@code obj} if not {@code null}.
    1244     * @throws NullPointerException     if {@code obj} is {@code null}.
    1245     * @throws IllegalArgumentException if {@code obj} is empty per {@link #isEmpty(Object)}.
    1246     * @see #isEmpty(Object)
    1247     * @since 3.12.0
    1248     */
    1249    public static <T> T  requireNonEmpty(final T obj) {
    1250        return requireNonEmpty(obj, "object");
    1251    }
    1252
    1253    /**
    1254     * Checks that the specified object reference is not {@code null} or empty per {@link #isEmpty(Object)}. Use this
    1255     * method for validation, for example:
    1256     *
    1257     * <blockquote>
    1258     *
    1259     * <pre>
    1260     * public Foo(Bar bar) {
    1261     *     this.bar = Objects.requireNonEmpty(bar, "bar");
    1262     * }
    1263     * </pre>
    1264     *
    1265     * </blockquote>
    1266     *
    1267     * @param <T> the type of the reference.
    1268     * @param obj the object reference to check for nullity.
    1269     * @param message the exception message.
    1270     * @return {@code obj} if not {@code null}.
    1271     * @throws NullPointerException     if {@code obj} is {@code null}.
    1272     * @throws IllegalArgumentException if {@code obj} is empty per {@link #isEmpty(Object)}.
    1273     * @see #isEmpty(Object)
    1274     * @since 3.12.0
    1275     */
    1276    public static <T> T requireNonEmpty(final T obj, final String message) {
    1277        // check for null first to give the most precise exception.
    1278        Objects.requireNonNull(obj, message);
    1279        if (isEmpty(obj)) {
    1280            throw new IllegalArgumentException(message);
    1281        }
    1282        return obj;
    1283    }
    1284
    1285    /**
    1286     * Gets the {@code toString} of an {@link Object} returning
    1287     * an empty string ("") if {@code null} input.
    1288     *
    1289     * <pre>
    1290     * ObjectUtils.toString(null)         = ""
    1291     * ObjectUtils.toString("")           = ""
    1292     * ObjectUtils.toString("bat")        = "bat"
    1293     * ObjectUtils.toString(Boolean.TRUE) = "true"
    1294     * </pre>
    1295     *
    1296     * @see StringUtils#defaultString(String)
    1297     * @see String#valueOf(Object)
    1298     * @param obj  the Object to {@code toString}, may be null
    1299     * @return the passed in Object's toString, or {@code ""} if {@code null} input
    1300     * @since 2.0
    1301     * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be
    1302     * removed in future releases. Note however that said method will return "null" for null references, while this
    1303     * method returns an empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")}
    1304     */
    1305    @Deprecated
    1306    public static String toString(final Object obj) {
    1307        return obj == null ? StringUtils.EMPTY : obj.toString();
    1308    }
    1309
    1310    /**
    1311     * Gets the {@code toString} of an {@link Object} returning
    1312     * a specified text if {@code null} input.
    1313     *
    1314     * <pre>
    1315     * ObjectUtils.toString(null, null)           = null
    1316     * ObjectUtils.toString(null, "null")         = "null"
    1317     * ObjectUtils.toString("", "null")           = ""
    1318     * ObjectUtils.toString("bat", "null")        = "bat"
    1319     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
    1320     * </pre>
    1321     *
    1322     * @see StringUtils#defaultString(String,String)
    1323     * @see String#valueOf(Object)
    1324     * @param obj  the Object to {@code toString}, may be null
    1325     * @param nullStr  the String to return if {@code null} input, may be null
    1326     * @return the passed in Object's toString, or {@code nullStr} if {@code null} input
    1327     * @since 2.0
    1328     * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and
    1329     * will be removed in future releases.
    1330     */
    1331    @Deprecated
    1332    public static String toString(final Object obj, final String nullStr) {
    1333        return obj == null ? nullStr : obj.toString();
    1334    }
    1335
    1336    /**
    1337     * Gets the {@code toString} of an {@link Object} returning
    1338     * a specified text if {@code null} input.
    1339     *
    1340     * <pre>
    1341     * ObjectUtils.toString(obj, () -&gt; expensive())
    1342     * </pre>
    1343     * <pre>
    1344     * ObjectUtils.toString(null, () -&gt; expensive())         = result of expensive()
    1345     * ObjectUtils.toString(null, () -&gt; expensive())         = result of expensive()
    1346     * ObjectUtils.toString("", () -&gt; expensive())           = ""
    1347     * ObjectUtils.toString("bat", () -&gt; expensive())        = "bat"
    1348     * ObjectUtils.toString(Boolean.TRUE, () -&gt; expensive()) = "true"
    1349     * </pre>
    1350     *
    1351     * @param obj  the Object to {@code toString}, may be null
    1352     * @param supplier  the Supplier of String used on {@code null} input, may be null
    1353     * @return the passed in Object's toString, or {@code nullStr} if {@code null} input
    1354     * @since 3.11
    1355     */
    1356    public static String toString(final Object obj, final Supplier<String> supplier) {
    1357        return obj == null ? Suppliers.get(supplier) : obj.toString();
    1358    }
    1359
    1360    /**
    1361     * Calls {@link Object#wait(long, int)} for the given Duration.
    1362     *
    1363     * @param obj The receiver of the wait call.
    1364     * @param duration How long to wait.
    1365     * @throws IllegalArgumentException if the timeout duration is negative.
    1366     * @throws IllegalMonitorStateException if the current thread is not the owner of the {@code obj}'s monitor.
    1367     * @throws InterruptedException if any thread interrupted the current thread before or while the current thread was
    1368     *         waiting for a notification. The <em>interrupted status</em> of the current thread is cleared when this
    1369     *         exception is thrown.
    1370     * @see Object#wait(long, int)
    1371     * @since 3.12.0
    1372     */
    1373    public static void wait(final Object obj, final Duration duration) throws InterruptedException {
    1374        DurationUtils.accept(obj::wait, DurationUtils.zeroIfNull(duration));
    1375    }
    1376
    1377    /**
    1378     * {@link ObjectUtils} instances should NOT be constructed in
    1379     * standard programming. Instead, the static methods on the class should
    1380     * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.
    1381     *
    1382     * <p>This constructor is public to permit tools that require a JavaBean
    1383     * instance to operate.</p>
    1384     */
    1385    public ObjectUtils() {
    1386    }
    1387
    1388}