ObjectUtils.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.lang3;

  18. import java.io.IOException;
  19. import java.io.Serializable;
  20. import java.lang.reflect.Array;
  21. import java.time.Duration;
  22. import java.util.ArrayList;
  23. import java.util.Collection;
  24. import java.util.Collections;
  25. import java.util.Comparator;
  26. import java.util.HashMap;
  27. import java.util.Hashtable;
  28. import java.util.Map;
  29. import java.util.Objects;
  30. import java.util.Optional;
  31. import java.util.TreeSet;
  32. import java.util.function.Supplier;
  33. import java.util.stream.Stream;

  34. import org.apache.commons.lang3.exception.CloneFailedException;
  35. import org.apache.commons.lang3.function.Suppliers;
  36. import org.apache.commons.lang3.mutable.MutableInt;
  37. import org.apache.commons.lang3.stream.Streams;
  38. import org.apache.commons.lang3.text.StrBuilder;
  39. import org.apache.commons.lang3.time.DurationUtils;

  40. /**
  41.  * Operations on {@link Object}.
  42.  *
  43.  * <p>This class tries to handle {@code null} input gracefully.
  44.  * An exception will generally not be thrown for a {@code null} input.
  45.  * Each method documents its behavior in more detail.</p>
  46.  *
  47.  * <p>#ThreadSafe#</p>
  48.  * @since 1.0
  49.  */
  50. //@Immutable
  51. @SuppressWarnings("deprecation") // deprecated class StrBuilder is imported
  52. // because it is part of the signature of deprecated methods
  53. public class ObjectUtils {

  54.     /**
  55.      * Class used as a null placeholder where {@code null}
  56.      * has another meaning.
  57.      *
  58.      * <p>For example, in a {@link HashMap} the
  59.      * {@link java.util.HashMap#get(Object)} method returns
  60.      * {@code null} if the {@link Map} contains {@code null} or if there is
  61.      * no matching key. The {@code null} placeholder can be used to distinguish
  62.      * between these two cases.</p>
  63.      *
  64.      * <p>Another example is {@link Hashtable}, where {@code null}
  65.      * cannot be stored.</p>
  66.      */
  67.     public static class Null implements Serializable {
  68.         /**
  69.          * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0
  70.          *
  71.          * @see java.io.Serializable
  72.          */
  73.         private static final long serialVersionUID = 7092611880189329093L;

  74.         /**
  75.          * Restricted constructor - singleton.
  76.          */
  77.         Null() {
  78.         }

  79.         /**
  80.          * Ensure Singleton after serialization.
  81.          *
  82.          * @return the singleton value
  83.          */
  84.         private Object readResolve() {
  85.             return NULL;
  86.         }
  87.     }

  88.     private static final char AT_SIGN = '@';

  89.     /**
  90.      * Singleton used as a {@code null} placeholder where
  91.      * {@code null} has another meaning.
  92.      *
  93.      * <p>For example, in a {@link HashMap} the
  94.      * {@link java.util.HashMap#get(Object)} method returns
  95.      * {@code null} if the {@link Map} contains {@code null} or if there
  96.      * is no matching key. The {@code null} placeholder can be used to
  97.      * distinguish between these two cases.</p>
  98.      *
  99.      * <p>Another example is {@link Hashtable}, where {@code null}
  100.      * cannot be stored.</p>
  101.      *
  102.      * <p>This instance is Serializable.</p>
  103.      */
  104.     public static final Null NULL = new Null();

  105.     /**
  106.      * Tests if all values in the array are not {@code nulls}.
  107.      *
  108.      * <p>
  109.      * If any value is {@code null} or the array is {@code null} then
  110.      * {@code false} is returned. If all elements in array are not
  111.      * {@code null} or the array is empty (contains no elements) {@code true}
  112.      * is returned.
  113.      * </p>
  114.      *
  115.      * <pre>
  116.      * ObjectUtils.allNotNull(*)             = true
  117.      * ObjectUtils.allNotNull(*, *)          = true
  118.      * ObjectUtils.allNotNull(null)          = false
  119.      * ObjectUtils.allNotNull(null, null)    = false
  120.      * ObjectUtils.allNotNull(null, *)       = false
  121.      * ObjectUtils.allNotNull(*, null)       = false
  122.      * ObjectUtils.allNotNull(*, *, null, *) = false
  123.      * </pre>
  124.      *
  125.      * @param values  the values to test, may be {@code null} or empty
  126.      * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null},
  127.      * {@code true} if all values in the array are not {@code null}s or array contains no elements.
  128.      * @since 3.5
  129.      */
  130.     public static boolean allNotNull(final Object... values) {
  131.         return values != null && Stream.of(values).noneMatch(Objects::isNull);
  132.     }

  133.     /**
  134.      * Tests if all values in the given array are {@code null}.
  135.      *
  136.      * <p>
  137.      * If all the values are {@code null} or the array is {@code null}
  138.      * or empty, then {@code true} is returned, otherwise {@code false} is returned.
  139.      * </p>
  140.      *
  141.      * <pre>
  142.      * ObjectUtils.allNull(*)                = false
  143.      * ObjectUtils.allNull(*, null)          = false
  144.      * ObjectUtils.allNull(null, *)          = false
  145.      * ObjectUtils.allNull(null, null, *, *) = false
  146.      * ObjectUtils.allNull(null)             = true
  147.      * ObjectUtils.allNull(null, null)       = true
  148.      * </pre>
  149.      *
  150.      * @param values  the values to test, may be {@code null} or empty
  151.      * @return {@code true} if all values in the array are {@code null}s,
  152.      * {@code false} if there is at least one non-null value in the array.
  153.      * @since 3.11
  154.      */
  155.     public static boolean allNull(final Object... values) {
  156.         return !anyNotNull(values);
  157.     }

  158.     /**
  159.      * Tests if any value in the given array is not {@code null}.
  160.      *
  161.      * <p>
  162.      * If all the values are {@code null} or the array is {@code null}
  163.      * or empty then {@code false} is returned. Otherwise {@code true} is returned.
  164.      * </p>
  165.      *
  166.      * <pre>
  167.      * ObjectUtils.anyNotNull(*)                = true
  168.      * ObjectUtils.anyNotNull(*, null)          = true
  169.      * ObjectUtils.anyNotNull(null, *)          = true
  170.      * ObjectUtils.anyNotNull(null, null, *, *) = true
  171.      * ObjectUtils.anyNotNull(null)             = false
  172.      * ObjectUtils.anyNotNull(null, null)       = false
  173.      * </pre>
  174.      *
  175.      * @param values  the values to test, may be {@code null} or empty
  176.      * @return {@code true} if there is at least one non-null value in the array,
  177.      * {@code false} if all values in the array are {@code null}s.
  178.      * If the array is {@code null} or empty {@code false} is also returned.
  179.      * @since 3.5
  180.      */
  181.     public static boolean anyNotNull(final Object... values) {
  182.         return firstNonNull(values) != null;
  183.     }

  184.     /**
  185.      * Tests if any value in the given array is {@code null}.
  186.      *
  187.      * <p>
  188.      * If any of the values are {@code null} or the array is {@code null},
  189.      * then {@code true} is returned, otherwise {@code false} is returned.
  190.      * </p>
  191.      *
  192.      * <pre>
  193.      * ObjectUtils.anyNull(*)             = false
  194.      * ObjectUtils.anyNull(*, *)          = false
  195.      * ObjectUtils.anyNull(null)          = true
  196.      * ObjectUtils.anyNull(null, null)    = true
  197.      * ObjectUtils.anyNull(null, *)       = true
  198.      * ObjectUtils.anyNull(*, null)       = true
  199.      * ObjectUtils.anyNull(*, *, null, *) = true
  200.      * </pre>
  201.      *
  202.      * @param values  the values to test, may be {@code null} or empty
  203.      * @return {@code true} if there is at least one {@code null} value in the array,
  204.      * {@code false} if all the values are non-null.
  205.      * If the array is {@code null} or empty, {@code true} is also returned.
  206.      * @since 3.11
  207.      */
  208.     public static boolean anyNull(final Object... values) {
  209.         return !allNotNull(values);
  210.     }

  211.     /**
  212.      * Clones an object.
  213.      *
  214.      * @param <T> the type of the object
  215.      * @param obj  the object to clone, null returns null
  216.      * @return the clone if the object implements {@link Cloneable} otherwise {@code null}
  217.      * @throws CloneFailedException if the object is cloneable and the clone operation fails
  218.      * @since 3.0
  219.      */
  220.     public static <T> T clone(final T obj) {
  221.         if (obj instanceof Cloneable) {
  222.             final Object result;
  223.             final Class<? extends Object> objClass = obj.getClass();
  224.             if (isArray(obj)) {
  225.                 final Class<?> componentType = objClass.getComponentType();
  226.                 if (componentType.isPrimitive()) {
  227.                     int length = Array.getLength(obj);
  228.                     result = Array.newInstance(componentType, length);
  229.                     while (length-- > 0) {
  230.                         Array.set(result, length, Array.get(obj, length));
  231.                     }
  232.                 } else {
  233.                     result = ((Object[]) obj).clone();
  234.                 }
  235.             } else {
  236.                 try {
  237.                     result = objClass.getMethod("clone").invoke(obj);
  238.                 } catch (final ReflectiveOperationException e) {
  239.                     throw new CloneFailedException("Exception cloning Cloneable type " + objClass.getName(), e);
  240.                 }
  241.             }
  242.             return (T) result;
  243.         }

  244.         return null;
  245.     }

  246.     /**
  247.      * Clones an object if possible.
  248.      *
  249.      * <p>This method is similar to {@link #clone(Object)}, but will return the provided
  250.      * instance as the return value instead of {@code null} if the instance
  251.      * is not cloneable. This is more convenient if the caller uses different
  252.      * implementations (e.g. of a service) and some of the implementations do not allow concurrent
  253.      * processing or have state. In such cases the implementation can simply provide a proper
  254.      * clone implementation and the caller's code does not have to change.</p>
  255.      *
  256.      * @param <T> the type of the object
  257.      * @param obj  the object to clone, null returns null
  258.      * @return the clone if the object implements {@link Cloneable} otherwise the object itself
  259.      * @throws CloneFailedException if the object is cloneable and the clone operation fails
  260.      * @since 3.0
  261.      */
  262.     public static <T> T cloneIfPossible(final T obj) {
  263.         final T clone = clone(obj);
  264.         return clone == null ? obj : clone;
  265.     }

  266.     /**
  267.      * Null safe comparison of Comparables.
  268.      * {@code null} is assumed to be less than a non-{@code null} value.
  269.      * <p>TODO Move to ComparableUtils.</p>
  270.      *
  271.      * @param <T> type of the values processed by this method
  272.      * @param c1  the first comparable, may be null
  273.      * @param c2  the second comparable, may be null
  274.      * @return a negative value if c1 &lt; c2, zero if c1 = c2
  275.      *  and a positive value if c1 &gt; c2
  276.      */
  277.     public static <T extends Comparable<? super T>> int compare(final T c1, final T c2) {
  278.         return compare(c1, c2, false);
  279.     }

  280.     /**
  281.      * Null safe comparison of Comparables.
  282.      * <p>TODO Move to ComparableUtils.</p>
  283.      *
  284.      * @param <T> type of the values processed by this method
  285.      * @param c1  the first comparable, may be null
  286.      * @param c2  the second comparable, may be null
  287.      * @param nullGreater if true {@code null} is considered greater
  288.      *  than a non-{@code null} value or if false {@code null} is
  289.      *  considered less than a Non-{@code null} value
  290.      * @return a negative value if c1 &lt; c2, zero if c1 = c2
  291.      *  and a positive value if c1 &gt; c2
  292.      * @see java.util.Comparator#compare(Object, Object)
  293.      */
  294.     public static <T extends Comparable<? super T>> int compare(final T c1, final T c2, final boolean nullGreater) {
  295.         if (c1 == c2) {
  296.             return 0;
  297.         }
  298.         if (c1 == null) {
  299.             return nullGreater ? 1 : -1;
  300.         }
  301.         if (c2 == null) {
  302.             return nullGreater ? -1 : 1;
  303.         }
  304.         return c1.compareTo(c2);
  305.     }

  306.     /**
  307.      * Returns the provided value unchanged.
  308.      * This can prevent javac from inlining a constant
  309.      * field, e.g.,
  310.      *
  311.      * <pre>
  312.      *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
  313.      * </pre>
  314.      *
  315.      * This way any jars that refer to this field do not
  316.      * have to recompile themselves if the field's value
  317.      * changes at some future date.
  318.      *
  319.      * @param v the boolean value to return
  320.      * @return the boolean v, unchanged
  321.      * @since 3.2
  322.      */
  323.     public static boolean CONST(final boolean v) {
  324.         return v;
  325.     }

  326.     /**
  327.      * Returns the provided value unchanged.
  328.      * This can prevent javac from inlining a constant
  329.      * field, e.g.,
  330.      *
  331.      * <pre>
  332.      *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
  333.      * </pre>
  334.      *
  335.      * This way any jars that refer to this field do not
  336.      * have to recompile themselves if the field's value
  337.      * changes at some future date.
  338.      *
  339.      * @param v the byte value to return
  340.      * @return the byte v, unchanged
  341.      * @since 3.2
  342.      */
  343.     public static byte CONST(final byte v) {
  344.         return v;
  345.     }

  346.     /**
  347.      * Returns the provided value unchanged.
  348.      * This can prevent javac from inlining a constant
  349.      * field, e.g.,
  350.      *
  351.      * <pre>
  352.      *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
  353.      * </pre>
  354.      *
  355.      * This way any jars that refer to this field do not
  356.      * have to recompile themselves if the field's value
  357.      * changes at some future date.
  358.      *
  359.      * @param v the char value to return
  360.      * @return the char v, unchanged
  361.      * @since 3.2
  362.      */
  363.     public static char CONST(final char v) {
  364.         return v;
  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 double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
  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 double value to return
  380.      * @return the double v, unchanged
  381.      * @since 3.2
  382.      */
  383.     public static double CONST(final double v) {
  384.         return v;
  385.     }

  386.     /**
  387.      * Returns the provided value unchanged.
  388.      * This can prevent javac from inlining a constant
  389.      * field, e.g.,
  390.      *
  391.      * <pre>
  392.      *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
  393.      * </pre>
  394.      *
  395.      * This way any jars that refer to this field do not
  396.      * have to recompile themselves if the field's value
  397.      * changes at some future date.
  398.      *
  399.      * @param v the float value to return
  400.      * @return the float v, unchanged
  401.      * @since 3.2
  402.      */
  403.     public static float CONST(final float v) {
  404.         return v;
  405.     }

  406.     /**
  407.      * Returns the provided value unchanged.
  408.      * This can prevent javac from inlining a constant
  409.      * field, e.g.,
  410.      *
  411.      * <pre>
  412.      *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
  413.      * </pre>
  414.      *
  415.      * This way any jars that refer to this field do not
  416.      * have to recompile themselves if the field's value
  417.      * changes at some future date.
  418.      *
  419.      * @param v the int value to return
  420.      * @return the int v, unchanged
  421.      * @since 3.2
  422.      */
  423.     public static int CONST(final int v) {
  424.         return v;
  425.     }

  426.     /**
  427.      * Returns the provided value unchanged.
  428.      * This can prevent javac from inlining a constant
  429.      * field, e.g.,
  430.      *
  431.      * <pre>
  432.      *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
  433.      * </pre>
  434.      *
  435.      * This way any jars that refer to this field do not
  436.      * have to recompile themselves if the field's value
  437.      * changes at some future date.
  438.      *
  439.      * @param v the long value to return
  440.      * @return the long v, unchanged
  441.      * @since 3.2
  442.      */
  443.     public static long CONST(final long v) {
  444.         return v;
  445.     }

  446.     /**
  447.      * Returns the provided value unchanged.
  448.      * This can prevent javac from inlining a constant
  449.      * field, e.g.,
  450.      *
  451.      * <pre>
  452.      *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
  453.      * </pre>
  454.      *
  455.      * This way any jars that refer to this field do not
  456.      * have to recompile themselves if the field's value
  457.      * changes at some future date.
  458.      *
  459.      * @param v the short value to return
  460.      * @return the short v, unchanged
  461.      * @since 3.2
  462.      */
  463.     public static short CONST(final short v) {
  464.         return v;
  465.     }

  466.     /**
  467.      * Returns the provided value unchanged.
  468.      * This can prevent javac from inlining a constant
  469.      * field, e.g.,
  470.      *
  471.      * <pre>
  472.      *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
  473.      * </pre>
  474.      *
  475.      * This way any jars that refer to this field do not
  476.      * have to recompile themselves if the field's value
  477.      * changes at some future date.
  478.      *
  479.      * @param <T> the Object type
  480.      * @param v the genericized Object value to return (typically a String).
  481.      * @return the genericized Object v, unchanged (typically a String).
  482.      * @since 3.2
  483.      */
  484.     public static <T> T CONST(final T v) {
  485.         return v;
  486.     }

  487.     /**
  488.      * Returns the provided value unchanged.
  489.      * This can prevent javac from inlining a constant
  490.      * field, e.g.,
  491.      *
  492.      * <pre>
  493.      *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
  494.      * </pre>
  495.      *
  496.      * This way any jars that refer to this field do not
  497.      * have to recompile themselves if the field's value
  498.      * changes at some future date.
  499.      *
  500.      * @param v the byte literal (as an int) value to return
  501.      * @throws IllegalArgumentException if the value passed to v
  502.      *         is larger than a byte, that is, smaller than -128 or
  503.      *         larger than 127.
  504.      * @return the byte v, unchanged
  505.      * @since 3.2
  506.      */
  507.     public static byte CONST_BYTE(final int v) {
  508.         if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) {
  509.             throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]");
  510.         }
  511.         return (byte) v;
  512.     }

  513.     /**
  514.      * Returns the provided value unchanged.
  515.      * This can prevent javac from inlining a constant
  516.      * field, e.g.,
  517.      *
  518.      * <pre>
  519.      *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
  520.      * </pre>
  521.      *
  522.      * This way any jars that refer to this field do not
  523.      * have to recompile themselves if the field's value
  524.      * changes at some future date.
  525.      *
  526.      * @param v the short literal (as an int) value to return
  527.      * @throws IllegalArgumentException if the value passed to v
  528.      *         is larger than a short, that is, smaller than -32768 or
  529.      *         larger than 32767.
  530.      * @return the byte v, unchanged
  531.      * @since 3.2
  532.      */
  533.     public static short CONST_SHORT(final int v) {
  534.         if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) {
  535.             throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]");
  536.         }
  537.         return (short) v;
  538.     }

  539.     /**
  540.      * Returns a default value if the object passed is {@code null}.
  541.      *
  542.      * <pre>
  543.      * ObjectUtils.defaultIfNull(null, null)      = null
  544.      * ObjectUtils.defaultIfNull(null, "")        = ""
  545.      * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
  546.      * ObjectUtils.defaultIfNull("abc", *)        = "abc"
  547.      * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
  548.      * </pre>
  549.      *
  550.      * @param <T> the type of the object
  551.      * @param object  the {@link Object} to test, may be {@code null}
  552.      * @param defaultValue  the default value to return, may be {@code null}
  553.      * @return {@code object} if it is not {@code null}, defaultValue otherwise
  554.      * TODO Rename to getIfNull in 4.0
  555.      */
  556.     public static <T> T defaultIfNull(final T object, final T defaultValue) {
  557.         return object != null ? object : defaultValue;
  558.     }

  559.     // Null-safe equals/hashCode
  560.     /**
  561.      * Compares two objects for equality, where either one or both
  562.      * objects may be {@code null}.
  563.      *
  564.      * <pre>
  565.      * ObjectUtils.equals(null, null)                  = true
  566.      * ObjectUtils.equals(null, "")                    = false
  567.      * ObjectUtils.equals("", null)                    = false
  568.      * ObjectUtils.equals("", "")                      = true
  569.      * ObjectUtils.equals(Boolean.TRUE, null)          = false
  570.      * ObjectUtils.equals(Boolean.TRUE, "true")        = false
  571.      * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
  572.      * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
  573.      * </pre>
  574.      *
  575.      * @param object1  the first object, may be {@code null}
  576.      * @param object2  the second object, may be {@code null}
  577.      * @return {@code true} if the values of both objects are the same
  578.      * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will
  579.      * be removed from future releases.
  580.      */
  581.     @Deprecated
  582.     public static boolean equals(final Object object1, final Object object2) {
  583.         return Objects.equals(object1, object2);
  584.     }

  585.     /**
  586.      * Returns the first value in the array which is not {@code null}.
  587.      * If all the values are {@code null} or the array is {@code null}
  588.      * or empty then {@code null} is returned.
  589.      *
  590.      * <pre>
  591.      * ObjectUtils.firstNonNull(null, null)      = null
  592.      * ObjectUtils.firstNonNull(null, "")        = ""
  593.      * ObjectUtils.firstNonNull(null, null, "")  = ""
  594.      * ObjectUtils.firstNonNull(null, "zz")      = "zz"
  595.      * ObjectUtils.firstNonNull("abc", *)        = "abc"
  596.      * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
  597.      * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
  598.      * ObjectUtils.firstNonNull()                = null
  599.      * </pre>
  600.      *
  601.      * @param <T> the component type of the array
  602.      * @param values  the values to test, may be {@code null} or empty
  603.      * @return the first value from {@code values} which is not {@code null},
  604.      *  or {@code null} if there are no non-null values
  605.      * @since 3.0
  606.      */
  607.     @SafeVarargs
  608.     public static <T> T firstNonNull(final T... values) {
  609.         return Streams.of(values).filter(Objects::nonNull).findFirst().orElse(null);
  610.     }

  611.     /**
  612.      * Delegates to {@link Object#getClass()} using generics.
  613.      *
  614.      * @param <T> The argument type or null.
  615.      * @param object The argument.
  616.      * @return The argument's Class or null.
  617.      * @since 3.13.0
  618.      */
  619.     @SuppressWarnings("unchecked")
  620.     public static <T> Class<T> getClass(final T object) {
  621.         return object == null ? null : (Class<T>) object.getClass();
  622.     }

  623.     /**
  624.      * Executes the given suppliers in order and returns the first return
  625.      * value where a value other than {@code null} is returned.
  626.      * Once a non-{@code null} value is obtained, all following suppliers are
  627.      * not executed anymore.
  628.      * If all the return values are {@code null} or no suppliers are provided
  629.      * then {@code null} is returned.
  630.      *
  631.      * <pre>
  632.      * ObjectUtils.firstNonNullLazy(null, () -&gt; null) = null
  633.      * ObjectUtils.firstNonNullLazy(() -&gt; null, () -&gt; "") = ""
  634.      * ObjectUtils.firstNonNullLazy(() -&gt; "", () -&gt; throw new IllegalStateException()) = ""
  635.      * ObjectUtils.firstNonNullLazy(() -&gt; null, () -&gt; "zz) = "zz"
  636.      * ObjectUtils.firstNonNullLazy() = null
  637.      * </pre>
  638.      *
  639.      * @param <T> the type of the return values
  640.      * @param suppliers  the suppliers returning the values to test.
  641.      *                   {@code null} values are ignored.
  642.      *                   Suppliers may return {@code null} or a value of type {@code T}
  643.      * @return the first return value from {@code suppliers} which is not {@code null},
  644.      *  or {@code null} if there are no non-null values
  645.      * @since 3.10
  646.      */
  647.     @SafeVarargs
  648.     public static <T> T getFirstNonNull(final Supplier<T>... suppliers) {
  649.         return Streams.of(suppliers).filter(Objects::nonNull).map(Supplier::get).filter(Objects::nonNull).findFirst().orElse(null);
  650.     }

  651.     /**
  652.      * Returns the given {@code object} is it is non-null, otherwise returns the Supplier's {@link Supplier#get()}
  653.      * value.
  654.      *
  655.      * <p>
  656.      * The caller responsible for thread-safety and exception handling of default value supplier.
  657.      * </p>
  658.      *
  659.      * <pre>
  660.      * ObjectUtils.getIfNull(null, () -&gt; null)     = null
  661.      * ObjectUtils.getIfNull(null, null)              = null
  662.      * ObjectUtils.getIfNull(null, () -&gt; "")       = ""
  663.      * ObjectUtils.getIfNull(null, () -&gt; "zz")     = "zz"
  664.      * ObjectUtils.getIfNull("abc", *)                = "abc"
  665.      * ObjectUtils.getIfNull(Boolean.TRUE, *)         = Boolean.TRUE
  666.      * </pre>
  667.      *
  668.      * @param <T> the type of the object
  669.      * @param object the {@link Object} to test, may be {@code null}
  670.      * @param defaultSupplier the default value to return, may be {@code null}
  671.      * @return {@code object} if it is not {@code null}, {@code defaultValueSupplier.get()} otherwise
  672.      * @since 3.10
  673.      */
  674.     public static <T> T getIfNull(final T object, final Supplier<T> defaultSupplier) {
  675.         return object != null ? object : Suppliers.get(defaultSupplier);
  676.     }

  677.     /**
  678.      * Gets the hash code of an object returning zero when the
  679.      * 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
  690.      * removed in future releases
  691.      */
  692.     @Deprecated
  693.     public static int hashCode(final Object obj) {
  694.         // hashCode(Object) for performance vs. hashCodeMulti(Object[]), as hash code is often critical
  695.         return Objects.hashCode(obj);
  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.      * Gets the hash code for multiple objects.
  712.      *
  713.      * <p>This allows a hash code to be rapidly calculated for a number of objects.
  714.      * The hash code for a single object is the <em>not</em> same as {@link #hashCode(Object)}.
  715.      * The hash code for multiple objects is the same as that calculated by an
  716.      * {@link ArrayList} containing the specified objects.</p>
  717.      *
  718.      * <pre>
  719.      * ObjectUtils.hashCodeMulti()                 = 1
  720.      * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
  721.      * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
  722.      * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
  723.      * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
  724.      * </pre>
  725.      *
  726.      * @param objects  the objects to obtain the hash code of, may be {@code null}
  727.      * @return the hash code of the objects, or zero if null
  728.      * @since 3.0
  729.      * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be
  730.      * 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.      * Returns the hexadecimal hash code for the given object per {@link System#identityHashCode(Object)}.
  745.      * <p>
  746.      * Short hand for {@code Integer.toHexString(System.identityHashCode(object))}.
  747.      * </p>
  748.      *
  749.      * @param object object for which the hashCode is to be calculated
  750.      * @return Hash code in hexadecimal format.
  751.      * @since 3.13.0
  752.      */
  753.     public static String identityHashCodeHex(final Object object) {
  754.         return Integer.toHexString(System.identityHashCode(object));
  755.     }

  756.     /**
  757.      * Appends the toString that would be produced by {@link Object}
  758.      * if a class did not override toString itself. {@code null}
  759.      * will throw a NullPointerException for either of the two parameters.
  760.      *
  761.      * <pre>
  762.      * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23")
  763.      * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
  764.      * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
  765.      * </pre>
  766.      *
  767.      * @param appendable  the appendable to append to
  768.      * @param object  the object to create a toString for
  769.      * @throws IOException if an I/O error occurs.
  770.      * @since 3.2
  771.      */
  772.     public static void identityToString(final Appendable appendable, final Object object) throws IOException {
  773.         Objects.requireNonNull(object, "object");
  774.         appendable.append(object.getClass().getName())
  775.               .append(AT_SIGN)
  776.               .append(identityHashCodeHex(object));
  777.     }

  778.     /**
  779.      * Gets the toString that would be produced by {@link Object}
  780.      * if a class did not override toString itself. {@code null}
  781.      * will return {@code null}.
  782.      *
  783.      * <pre>
  784.      * ObjectUtils.identityToString(null)         = null
  785.      * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
  786.      * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
  787.      * </pre>
  788.      *
  789.      * @param object  the object to create a toString for, may be
  790.      *  {@code null}
  791.      * @return the default toString text, or {@code null} if
  792.      *  {@code null} passed in
  793.      */
  794.     public static String identityToString(final Object object) {
  795.         if (object == null) {
  796.             return null;
  797.         }
  798.         final String name = object.getClass().getName();
  799.         final String hexString = identityHashCodeHex(object);
  800.         final StringBuilder builder = new StringBuilder(name.length() + 1 + hexString.length());
  801.         // @formatter:off
  802.         builder.append(name)
  803.               .append(AT_SIGN)
  804.               .append(hexString);
  805.         // @formatter:on
  806.         return builder.toString();
  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.      * Appends the toString that would be produced by {@link Object}
  837.      * if a class did not override toString itself. {@code null}
  838.      * will throw a NullPointerException for either of the two parameters.
  839.      *
  840.      * <pre>
  841.      * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23")
  842.      * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
  843.      * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
  844.      * </pre>
  845.      *
  846.      * @param buffer  the buffer to append to
  847.      * @param object  the object to create a toString for
  848.      * @since 2.4
  849.      */
  850.     public static void identityToString(final StringBuffer buffer, final Object object) {
  851.         Objects.requireNonNull(object, "object");
  852.         final String name = object.getClass().getName();
  853.         final String hexString = identityHashCodeHex(object);
  854.         buffer.ensureCapacity(buffer.length() + name.length() + 1 + hexString.length());
  855.         buffer.append(name)
  856.               .append(AT_SIGN)
  857.               .append(hexString);
  858.     }

  859.     /**
  860.      * Appends the toString that would be produced by {@link Object}
  861.      * if a class did not override toString itself. {@code null}
  862.      * will throw a NullPointerException for either of the two parameters.
  863.      *
  864.      * <pre>
  865.      * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23")
  866.      * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
  867.      * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
  868.      * </pre>
  869.      *
  870.      * @param builder  the builder to append to
  871.      * @param object  the object to create a toString for
  872.      * @since 3.2
  873.      */
  874.     public static void identityToString(final StringBuilder builder, final Object object) {
  875.         Objects.requireNonNull(object, "object");
  876.         final String name = object.getClass().getName();
  877.         final String hexString = identityHashCodeHex(object);
  878.         builder.ensureCapacity(builder.length() +  name.length() + 1 + hexString.length());
  879.         builder.append(name)
  880.               .append(AT_SIGN)
  881.               .append(hexString);
  882.     }

  883.     // Constants (LANG-816):
  884.     /*
  885.         These methods ensure constants are not inlined by javac.
  886.         For example, typically a developer might declare a constant like so:

  887.             public final static int MAGIC_NUMBER = 5;

  888.         Should a different jar file refer to this, and the MAGIC_NUMBER
  889.         is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar
  890.         file will need to recompile itself.  This is because javac
  891.         typically inlines the primitive or String constant directly into
  892.         the bytecode, and removes the reference to the MAGIC_NUMBER field.

  893.         To help the other jar (so that it does not need to recompile
  894.         when constants are changed) the original developer can declare
  895.         their constant using one of the CONST() utility methods, instead:

  896.             public final static int MAGIC_NUMBER = CONST(5);
  897.      */

  898.     /**
  899.      * Tests whether the given object is an Object array or a primitive array in a null-safe manner.
  900.      *
  901.      * <p>
  902.      * A {@code null} {@code object} Object will return {@code false}.
  903.      * </p>
  904.      *
  905.      * <pre>
  906.      * ObjectUtils.isArray(null)             = false
  907.      * ObjectUtils.isArray("")               = false
  908.      * ObjectUtils.isArray("ab")             = false
  909.      * ObjectUtils.isArray(new int[]{})      = true
  910.      * ObjectUtils.isArray(new int[]{1,2,3}) = true
  911.      * ObjectUtils.isArray(1234)             = false
  912.      * </pre>
  913.      *
  914.      * @param object the object to check, may be {@code null}
  915.      * @return {@code true} if the object is an {@code array}, {@code false} otherwise
  916.      * @since 3.13.0
  917.      */
  918.     public static boolean isArray(final Object object) {
  919.         return object != null && object.getClass().isArray();
  920.     }

  921.     /**
  922.      * Tests if an Object is empty or null.
  923.      *
  924.      * The following types are supported:
  925.      * <ul>
  926.      * <li>{@link CharSequence}: Considered empty if its length is zero.</li>
  927.      * <li>{@link Array}: Considered empty if its length is zero.</li>
  928.      * <li>{@link Collection}: Considered empty if it has zero elements.</li>
  929.      * <li>{@link Map}: Considered empty if it has zero key-value mappings.</li>
  930.      * <li>{@link Optional}: Considered empty if {@link Optional#isPresent} returns false, regardless of the "emptiness" of the contents.</li>
  931.      * </ul>
  932.      *
  933.      * <pre>
  934.      * ObjectUtils.isEmpty(null)             = true
  935.      * ObjectUtils.isEmpty("")               = true
  936.      * ObjectUtils.isEmpty("ab")             = false
  937.      * ObjectUtils.isEmpty(new int[]{})      = true
  938.      * ObjectUtils.isEmpty(new int[]{1,2,3}) = false
  939.      * ObjectUtils.isEmpty(1234)             = false
  940.      * ObjectUtils.isEmpty(1234)             = false
  941.      * ObjectUtils.isEmpty(Optional.of(""))  = false
  942.      * ObjectUtils.isEmpty(Optional.empty()) = true
  943.      * </pre>
  944.      *
  945.      * @param object  the {@link Object} to test, may be {@code null}
  946.      * @return {@code true} if the object has a supported type and is empty or null,
  947.      * {@code false} otherwise
  948.      * @since 3.9
  949.      */
  950.     public static boolean isEmpty(final Object object) {
  951.         if (object == null) {
  952.             return true;
  953.         }
  954.         if (object instanceof CharSequence) {
  955.             return ((CharSequence) object).length() == 0;
  956.         }
  957.         if (isArray(object)) {
  958.             return Array.getLength(object) == 0;
  959.         }
  960.         if (object instanceof Collection<?>) {
  961.             return ((Collection<?>) object).isEmpty();
  962.         }
  963.         if (object instanceof Map<?, ?>) {
  964.             return ((Map<?, ?>) object).isEmpty();
  965.         }
  966.         if (object instanceof Optional<?>) {
  967.             // TODO Java 11 Use Optional#isEmpty()
  968.             return !((Optional<?>) object).isPresent();
  969.         }
  970.         return false;
  971.     }

  972.     /**
  973.      * Tests if an Object is not empty and not null.
  974.      *
  975.      * The following types are supported:
  976.      * <ul>
  977.      * <li>{@link CharSequence}: Considered empty if its length is zero.</li>
  978.      * <li>{@link Array}: Considered empty if its length is zero.</li>
  979.      * <li>{@link Collection}: Considered empty if it has zero elements.</li>
  980.      * <li>{@link Map}: Considered empty if it has zero key-value mappings.</li>
  981.      * <li>{@link Optional}: Considered empty if {@link Optional#isPresent} returns false, regardless of the "emptiness" of the contents.</li>
  982.      * </ul>
  983.      *
  984.      * <pre>
  985.      * ObjectUtils.isNotEmpty(null)             = false
  986.      * ObjectUtils.isNotEmpty("")               = false
  987.      * ObjectUtils.isNotEmpty("ab")             = true
  988.      * ObjectUtils.isNotEmpty(new int[]{})      = false
  989.      * ObjectUtils.isNotEmpty(new int[]{1,2,3}) = true
  990.      * ObjectUtils.isNotEmpty(1234)             = true
  991.      * ObjectUtils.isNotEmpty(Optional.of(""))  = true
  992.      * ObjectUtils.isNotEmpty(Optional.empty()) = false
  993.      * </pre>
  994.      *
  995.      * @param object  the {@link Object} to test, may be {@code null}
  996.      * @return {@code true} if the object has an unsupported type or is not empty
  997.      * and not null, {@code false} otherwise
  998.      * @since 3.9
  999.      */
  1000.     public static boolean isNotEmpty(final Object object) {
  1001.         return !isEmpty(object);
  1002.     }

  1003.     /**
  1004.      * Null safe comparison of Comparables.
  1005.      * <p>TODO Move to ComparableUtils.</p>
  1006.      *
  1007.      * @param <T> type of the values processed by this method
  1008.      * @param values the set of comparable values, may be null
  1009.      * @return
  1010.      *  <ul>
  1011.      *   <li>If any objects are non-null and unequal, the greater object.
  1012.      *   <li>If all objects are non-null and equal, the first.
  1013.      *   <li>If any of the comparables are null, the greater of the non-null objects.
  1014.      *   <li>If all the comparables are null, null is returned.
  1015.      *  </ul>
  1016.      */
  1017.     @SafeVarargs
  1018.     public static <T extends Comparable<? super T>> T max(final T... values) {
  1019.         T result = null;
  1020.         if (values != null) {
  1021.             for (final T value : values) {
  1022.                 if (compare(value, result, false) > 0) {
  1023.                     result = value;
  1024.                 }
  1025.             }
  1026.         }
  1027.         return result;
  1028.     }

  1029.     /**
  1030.      * Find the "best guess" middle value among comparables. If there is an even
  1031.      * number of total values, the lower of the two middle values will be returned.
  1032.      * @param <T> type of values processed by this method
  1033.      * @param comparator to use for comparisons
  1034.      * @param items to compare
  1035.      * @return T at middle position
  1036.      * @throws NullPointerException if items or comparator is {@code null}
  1037.      * @throws IllegalArgumentException if items is empty or contains {@code null} values
  1038.      * @since 3.0.1
  1039.      */
  1040.     @SafeVarargs
  1041.     public static <T> T median(final Comparator<T> comparator, final T... items) {
  1042.         Validate.notEmpty(items, "null/empty items");
  1043.         Validate.noNullElements(items);
  1044.         Objects.requireNonNull(comparator, "comparator");
  1045.         final TreeSet<T> treeSet = new TreeSet<>(comparator);
  1046.         Collections.addAll(treeSet, items);
  1047.         return (T) treeSet.toArray()[(treeSet.size() - 1) / 2];
  1048.     }

  1049.     /**
  1050.      * Find the "best guess" middle value among comparables. If there is an even
  1051.      * number of total values, the lower of the two middle values will be returned.
  1052.      * @param <T> type of values processed by this method
  1053.      * @param items to compare
  1054.      * @return T at middle position
  1055.      * @throws NullPointerException if items is {@code null}
  1056.      * @throws IllegalArgumentException if items is empty or contains {@code null} values
  1057.      * @since 3.0.1
  1058.      */
  1059.     @SafeVarargs
  1060.     public static <T extends Comparable<? super T>> T median(final T... items) {
  1061.         Validate.notEmpty(items);
  1062.         Validate.noNullElements(items);
  1063.         final TreeSet<T> sort = new TreeSet<>();
  1064.         Collections.addAll(sort, items);
  1065.         return (T) sort.toArray()[(sort.size() - 1) / 2];
  1066.     }

  1067.     /**
  1068.      * Null safe comparison of Comparables.
  1069.      * <p>TODO Move to ComparableUtils.</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.      * Find the most frequently occurring item.
  1095.      *
  1096.      * @param <T> type of values processed by this method
  1097.      * @param items to check
  1098.      * @return most populous T, {@code null} if non-unique or no items supplied
  1099.      * @since 3.0.1
  1100.      */
  1101.     @SafeVarargs
  1102.     public static <T> T mode(final T... items) {
  1103.         if (ArrayUtils.isNotEmpty(items)) {
  1104.             final HashMap<T, MutableInt> occurrences = new HashMap<>(items.length);
  1105.             for (final T t : items) {
  1106.                 final MutableInt count = occurrences.get(t);
  1107.                 if (count == null) {
  1108.                     occurrences.put(t, new MutableInt(1));
  1109.                 } else {
  1110.                     count.increment();
  1111.                 }
  1112.             }
  1113.             T result = null;
  1114.             int max = 0;
  1115.             for (final Map.Entry<T, MutableInt> e : occurrences.entrySet()) {
  1116.                 final int cmp = e.getValue().intValue();
  1117.                 if (cmp == max) {
  1118.                     result = null;
  1119.                 } else if (cmp > max) {
  1120.                     max = cmp;
  1121.                     result = e.getKey();
  1122.                 }
  1123.             }
  1124.             return result;
  1125.         }
  1126.         return null;
  1127.     }

  1128.     /**
  1129.      * Compares two objects for inequality, where either one or both
  1130.      * objects may be {@code null}.
  1131.      *
  1132.      * <pre>
  1133.      * ObjectUtils.notEqual(null, null)                  = false
  1134.      * ObjectUtils.notEqual(null, "")                    = true
  1135.      * ObjectUtils.notEqual("", null)                    = true
  1136.      * ObjectUtils.notEqual("", "")                      = false
  1137.      * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
  1138.      * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
  1139.      * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
  1140.      * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
  1141.      * </pre>
  1142.      *
  1143.      * @param object1  the first object, may be {@code null}
  1144.      * @param object2  the second object, may be {@code null}
  1145.      * @return {@code false} if the values of both objects are the same
  1146.      */
  1147.     public static boolean notEqual(final Object object1, final Object object2) {
  1148.         return !Objects.equals(object1, object2);
  1149.     }

  1150.     /**
  1151.      * Checks that the specified object reference is not {@code null} or empty per {@link #isEmpty(Object)}. Use this
  1152.      * method for validation, for example:
  1153.      *
  1154.      * <blockquote>
  1155.      *
  1156.      * <pre>
  1157.      * public Foo(Bar bar) {
  1158.      *     this.bar = Objects.requireNonEmpty(bar);
  1159.      * }
  1160.      * </pre>
  1161.      *
  1162.      * </blockquote>
  1163.      *
  1164.      * @param <T> the type of the reference.
  1165.      * @param obj the object reference to check for nullity.
  1166.      * @return {@code obj} if not {@code null}.
  1167.      * @throws NullPointerException     if {@code obj} is {@code null}.
  1168.      * @throws IllegalArgumentException if {@code obj} is empty per {@link #isEmpty(Object)}.
  1169.      * @see #isEmpty(Object)
  1170.      * @since 3.12.0
  1171.      */
  1172.     public static <T> T  requireNonEmpty(final T obj) {
  1173.         return requireNonEmpty(obj, "object");
  1174.     }

  1175.     /**
  1176.      * Checks that the specified object reference is not {@code null} or empty per {@link #isEmpty(Object)}. Use this
  1177.      * method for validation, for example:
  1178.      *
  1179.      * <blockquote>
  1180.      *
  1181.      * <pre>
  1182.      * public Foo(Bar bar) {
  1183.      *     this.bar = Objects.requireNonEmpty(bar, "bar");
  1184.      * }
  1185.      * </pre>
  1186.      *
  1187.      * </blockquote>
  1188.      *
  1189.      * @param <T> the type of the reference.
  1190.      * @param obj the object reference to check for nullity.
  1191.      * @param message the exception message.
  1192.      * @return {@code obj} if not {@code null}.
  1193.      * @throws NullPointerException     if {@code obj} is {@code null}.
  1194.      * @throws IllegalArgumentException if {@code obj} is empty per {@link #isEmpty(Object)}.
  1195.      * @see #isEmpty(Object)
  1196.      * @since 3.12.0
  1197.      */
  1198.     public static <T> T requireNonEmpty(final T obj, final String message) {
  1199.         // check for null first to give the most precise exception.
  1200.         Objects.requireNonNull(obj, message);
  1201.         if (isEmpty(obj)) {
  1202.             throw new IllegalArgumentException(message);
  1203.         }
  1204.         return obj;
  1205.     }

  1206.     /**
  1207.      * Gets the {@code toString} of an {@link Object} returning
  1208.      * an empty string ("") if {@code null} input.
  1209.      *
  1210.      * <pre>
  1211.      * ObjectUtils.toString(null)         = ""
  1212.      * ObjectUtils.toString("")           = ""
  1213.      * ObjectUtils.toString("bat")        = "bat"
  1214.      * ObjectUtils.toString(Boolean.TRUE) = "true"
  1215.      * </pre>
  1216.      *
  1217.      * @see Objects#toString(Object)
  1218.      * @see Objects#toString(Object, String)
  1219.      * @see StringUtils#defaultString(String)
  1220.      * @see String#valueOf(Object)
  1221.      * @param obj  the Object to {@code toString}, may be null
  1222.      * @return the passed in Object's toString, or {@code ""} if {@code null} input
  1223.      * @since 2.0
  1224.      * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be
  1225.      * removed in future releases. Note however that said method will return "null" for null references, while this
  1226.      * method returns an empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")}
  1227.      */
  1228.     @Deprecated
  1229.     public static String toString(final Object obj) {
  1230.         return Objects.toString(obj, StringUtils.EMPTY);
  1231.     }

  1232.     /**
  1233.      * Gets the {@code toString} of an {@link Object} returning
  1234.      * a specified text if {@code null} input.
  1235.      *
  1236.      * <pre>
  1237.      * ObjectUtils.toString(null, null)           = null
  1238.      * ObjectUtils.toString(null, "null")         = "null"
  1239.      * ObjectUtils.toString("", "null")           = ""
  1240.      * ObjectUtils.toString("bat", "null")        = "bat"
  1241.      * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
  1242.      * </pre>
  1243.      *
  1244.      * @see Objects#toString(Object)
  1245.      * @see Objects#toString(Object, String)
  1246.      * @see StringUtils#defaultString(String,String)
  1247.      * @see String#valueOf(Object)
  1248.      * @param obj  the Object to {@code toString}, may be null
  1249.      * @param nullStr  the String to return if {@code null} input, may be null
  1250.      * @return the passed in Object's toString, or {@code nullStr} if {@code null} input
  1251.      * @since 2.0
  1252.      * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and
  1253.      * will be removed in future releases.
  1254.      */
  1255.     @Deprecated
  1256.     public static String toString(final Object obj, final String nullStr) {
  1257.         return Objects.toString(obj, nullStr);
  1258.     }

  1259.     /**
  1260.      * Gets the {@code toString} of an {@link Supplier}'s {@link Supplier#get()} returning
  1261.      * a specified text if {@code null} input.
  1262.      *
  1263.      * <pre>
  1264.      * ObjectUtils.toString(() -&gt; obj, () -&gt; expensive())
  1265.      * </pre>
  1266.      * <pre>
  1267.      * ObjectUtils.toString(() -&gt; null, () -&gt; expensive())         = result of expensive()
  1268.      * ObjectUtils.toString(() -&gt; null, () -&gt; expensive())         = result of expensive()
  1269.      * ObjectUtils.toString(() -&gt; "", () -&gt; expensive())           = ""
  1270.      * ObjectUtils.toString(() -&gt; "bat", () -&gt; expensive())        = "bat"
  1271.      * ObjectUtils.toString(() -&gt; Boolean.TRUE, () -&gt; expensive()) = "true"
  1272.      * </pre>
  1273.      *
  1274.      * @param obj  the Object to {@code toString}, may be null
  1275.      * @param supplier  the Supplier of String used on {@code null} input, may be null
  1276.      * @return the passed in Object's toString, or {@code nullStr} if {@code null} input
  1277.      * @since 3.14.0
  1278.      */
  1279.     public static String toString(final Supplier<Object> obj, final Supplier<String> supplier) {
  1280.         return obj == null ? Suppliers.get(supplier) : toString(obj.get(), supplier);
  1281.     }

  1282.     /**
  1283.      * Gets the {@code toString} of an {@link Object} returning
  1284.      * a specified text if {@code null} input.
  1285.      *
  1286.      * <pre>
  1287.      * ObjectUtils.toString(obj, () -&gt; expensive())
  1288.      * </pre>
  1289.      * <pre>
  1290.      * ObjectUtils.toString(null, () -&gt; expensive())         = result of expensive()
  1291.      * ObjectUtils.toString(null, () -&gt; expensive())         = result of expensive()
  1292.      * ObjectUtils.toString("", () -&gt; expensive())           = ""
  1293.      * ObjectUtils.toString("bat", () -&gt; expensive())        = "bat"
  1294.      * ObjectUtils.toString(Boolean.TRUE, () -&gt; expensive()) = "true"
  1295.      * </pre>
  1296.      *
  1297.      * @param <T> the obj type (used to provide better source compatibility in 3.14.0).
  1298.      * @param obj  the Object to {@code toString}, may be null
  1299.      * @param supplier  the Supplier of String used on {@code null} input, may be null
  1300.      * @return the passed in Object's toString, or {@code nullStr} if {@code null} input
  1301.      * @since 3.11
  1302.      */
  1303.     public static <T> String toString(final T obj, final Supplier<String> supplier) {
  1304.         return obj == null ? Suppliers.get(supplier) : obj.toString();
  1305.     }

  1306.     /**
  1307.      * Calls {@link Object#wait(long, int)} for the given Duration.
  1308.      *
  1309.      * @param obj The receiver of the wait call.
  1310.      * @param duration How long to wait.
  1311.      * @throws IllegalArgumentException if the timeout duration is negative.
  1312.      * @throws IllegalMonitorStateException if the current thread is not the owner of the {@code obj}'s monitor.
  1313.      * @throws InterruptedException if any thread interrupted the current thread before or while the current thread was
  1314.      *         waiting for a notification. The <em>interrupted status</em> of the current thread is cleared when this
  1315.      *         exception is thrown.
  1316.      * @see Object#wait(long, int)
  1317.      * @since 3.12.0
  1318.      */
  1319.     public static void wait(final Object obj, final Duration duration) throws InterruptedException {
  1320.         DurationUtils.accept(obj::wait, DurationUtils.zeroIfNull(duration));
  1321.     }

  1322.     /**
  1323.      * {@link ObjectUtils} instances should NOT be constructed in
  1324.      * standard programming. Instead, the static methods on the class should
  1325.      * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.
  1326.      *
  1327.      * <p>This constructor is public to permit tools that require a JavaBean
  1328.      * instance to operate.</p>
  1329.      *
  1330.      * @deprecated TODO Make private in 4.0.
  1331.      */
  1332.     @Deprecated
  1333.     public ObjectUtils() {
  1334.         // empty
  1335.     }

  1336. }