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