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