001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.commons.lang3;
018    
019    import java.io.Serializable;
020    import java.lang.reflect.Array;
021    import java.lang.reflect.InvocationTargetException;
022    import java.lang.reflect.Method;
023    
024    import org.apache.commons.lang3.exception.CloneFailedException;
025    
026    /**
027     * <p>Operations on {@code Object}.</p>
028     *
029     * <p>This class tries to handle {@code null} input gracefully.
030     * An exception will generally not be thrown for a {@code null} input.
031     * Each method documents its behaviour in more detail.</p>
032     *
033     * <p>#ThreadSafe#</p>
034     * @since 1.0
035     * @version $Id: ObjectUtils.java 1144929 2011-07-10 18:26:16Z ggregory $
036     */
037    //@Immutable
038    public class ObjectUtils {
039    
040        /**
041         * <p>Singleton used as a {@code null} placeholder where
042         * {@code null} has another meaning.</p>
043         *
044         * <p>For example, in a {@code HashMap} the
045         * {@link java.util.HashMap#get(java.lang.Object)} method returns
046         * {@code null} if the {@code Map} contains {@code null} or if there
047         * is no matching key. The {@code Null} placeholder can be used to
048         * distinguish between these two cases.</p>
049         *
050         * <p>Another example is {@code Hashtable}, where {@code null}
051         * cannot be stored.</p>
052         *
053         * <p>This instance is Serializable.</p>
054         */
055        public static final Null NULL = new Null();
056    
057        /**
058         * <p>{@code ObjectUtils} instances should NOT be constructed in
059         * standard programming. Instead, the static methods on the class should
060         * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.</p>
061         *
062         * <p>This constructor is public to permit tools that require a JavaBean
063         * instance to operate.</p>
064         */
065        public ObjectUtils() {
066            super();
067        }
068    
069        // Defaulting
070        //-----------------------------------------------------------------------
071        /**
072         * <p>Returns a default value if the object passed is {@code null}.</p>
073         *
074         * <pre>
075         * ObjectUtils.defaultIfNull(null, null)      = null
076         * ObjectUtils.defaultIfNull(null, "")        = ""
077         * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
078         * ObjectUtils.defaultIfNull("abc", *)        = "abc"
079         * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
080         * </pre>
081         *
082         * @param <T> the type of the object
083         * @param object  the {@code Object} to test, may be {@code null}
084         * @param defaultValue  the default value to return, may be {@code null}
085         * @return {@code object} if it is not {@code null}, defaultValue otherwise
086         */
087        public static <T> T defaultIfNull(T object, T defaultValue) {
088            return object != null ? object : defaultValue;
089        }
090    
091        /**
092         * <p>Returns the first value in the array which is not {@code null}.
093         * If all the values are {@code null} or the array is {@code null}
094         * or empty then {@code null} is returned.</p>
095         *
096         * <pre>
097         * ObjectUtils.firstNonNull(null, null)      = null
098         * ObjectUtils.firstNonNull(null, "")        = ""
099         * ObjectUtils.firstNonNull(null, null, "")  = ""
100         * ObjectUtils.firstNonNull(null, "zz")      = "zz"
101         * ObjectUtils.firstNonNull("abc", *)        = "abc"
102         * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
103         * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
104         * ObjectUtils.firstNonNull()                = null
105         * </pre>
106         *
107         * @param <T> the component type of the array
108         * @param values  the values to test, may be {@code null} or empty
109         * @return the first value from {@code values} which is not {@code null},
110         *  or {@code null} if there are no non-null values
111         * @since 3.0
112         */
113        public static <T> T firstNonNull(T... values) {
114            if (values != null) {
115                for (T val : values) {
116                    if (val != null) {
117                        return val;
118                    }
119                }
120            }
121            return null;
122        }
123    
124        // Null-safe equals/hashCode
125        //-----------------------------------------------------------------------
126        /**
127         * <p>Compares two objects for equality, where either one or both
128         * objects may be {@code null}.</p>
129         *
130         * <pre>
131         * ObjectUtils.equals(null, null)                  = true
132         * ObjectUtils.equals(null, "")                    = false
133         * ObjectUtils.equals("", null)                    = false
134         * ObjectUtils.equals("", "")                      = true
135         * ObjectUtils.equals(Boolean.TRUE, null)          = false
136         * ObjectUtils.equals(Boolean.TRUE, "true")        = false
137         * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
138         * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
139         * </pre>
140         *
141         * @param object1  the first object, may be {@code null}
142         * @param object2  the second object, may be {@code null}
143         * @return {@code true} if the values of both objects are the same
144         */
145        public static boolean equals(Object object1, Object object2) {
146            if (object1 == object2) {
147                return true;
148            }
149            if ((object1 == null) || (object2 == null)) {
150                return false;
151            }
152            return object1.equals(object2);
153        }
154    
155        /**
156         * <p>Compares two objects for inequality, where either one or both
157         * objects may be {@code null}.</p>
158         *
159         * <pre>
160         * ObjectUtils.notEqual(null, null)                  = false
161         * ObjectUtils.notEqual(null, "")                    = true
162         * ObjectUtils.notEqual("", null)                    = true
163         * ObjectUtils.notEqual("", "")                      = false
164         * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
165         * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
166         * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
167         * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
168         * </pre>
169         *
170         * @param object1  the first object, may be {@code null}
171         * @param object2  the second object, may be {@code null}
172         * @return {@code false} if the values of both objects are the same
173         */
174        public static boolean notEqual(Object object1, Object object2) {
175            return ObjectUtils.equals(object1, object2) == false;
176        }
177    
178        /**
179         * <p>Gets the hash code of an object returning zero when the
180         * object is {@code null}.</p>
181         *
182         * <pre>
183         * ObjectUtils.hashCode(null)   = 0
184         * ObjectUtils.hashCode(obj)    = obj.hashCode()
185         * </pre>
186         *
187         * @param obj  the object to obtain the hash code of, may be {@code null}
188         * @return the hash code of the object, or zero if null
189         * @since 2.1
190         */
191        public static int hashCode(Object obj) {
192            // hashCode(Object) retained for performance, as hash code is often critical
193            return (obj == null) ? 0 : obj.hashCode();
194        }
195    
196        /**
197         * <p>Gets the hash code for multiple objects.</p>
198         * 
199         * <p>This allows a hash code to be rapidly calculated for a number of objects.
200         * The hash code for a single object is the <em>not</em> same as {@link #hashCode(Object)}.
201         * The hash code for multiple objects is the same as that calculated by an
202         * {@code ArrayList} containing the specified objects.</p>
203         *
204         * <pre>
205         * ObjectUtils.hashCodeMulti()                 = 1
206         * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
207         * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
208         * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
209         * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
210         * </pre>
211         *
212         * @param objects  the objects to obtain the hash code of, may be {@code null}
213         * @return the hash code of the objects, or zero if null
214         * @since 3.0
215         */
216        public static int hashCodeMulti(Object... objects) {
217            int hash = 1;
218            if (objects != null) {
219                for (Object object : objects) {
220                    hash = hash * 31 + ObjectUtils.hashCode(object);
221                }
222            }
223            return hash;
224        }
225    
226        // Identity ToString
227        //-----------------------------------------------------------------------
228        /**
229         * <p>Gets the toString that would be produced by {@code Object}
230         * if a class did not override toString itself. {@code null}
231         * will return {@code null}.</p>
232         *
233         * <pre>
234         * ObjectUtils.identityToString(null)         = null
235         * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
236         * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
237         * </pre>
238         *
239         * @param object  the object to create a toString for, may be
240         *  {@code null}
241         * @return the default toString text, or {@code null} if
242         *  {@code null} passed in
243         */
244        public static String identityToString(Object object) {
245            if (object == null) {
246                return null;
247            }
248            StringBuffer buffer = new StringBuffer();
249            identityToString(buffer, object);
250            return buffer.toString();
251        }
252    
253        /**
254         * <p>Appends the toString that would be produced by {@code Object}
255         * if a class did not override toString itself. {@code null}
256         * will throw a NullPointerException for either of the two parameters. </p>
257         *
258         * <pre>
259         * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
260         * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
261         * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
262         * </pre>
263         *
264         * @param buffer  the buffer to append to
265         * @param object  the object to create a toString for
266         * @since 2.4
267         */
268        public static void identityToString(StringBuffer buffer, Object object) {
269            if (object == null) {
270                throw new NullPointerException("Cannot get the toString of a null identity");
271            }
272            buffer.append(object.getClass().getName())
273                  .append('@')
274                  .append(Integer.toHexString(System.identityHashCode(object)));
275        }
276    
277        // ToString
278        //-----------------------------------------------------------------------
279        /**
280         * <p>Gets the {@code toString} of an {@code Object} returning
281         * an empty string ("") if {@code null} input.</p>
282         *
283         * <pre>
284         * ObjectUtils.toString(null)         = ""
285         * ObjectUtils.toString("")           = ""
286         * ObjectUtils.toString("bat")        = "bat"
287         * ObjectUtils.toString(Boolean.TRUE) = "true"
288         * </pre>
289         *
290         * @see StringUtils#defaultString(String)
291         * @see String#valueOf(Object)
292         * @param obj  the Object to {@code toString}, may be null
293         * @return the passed in Object's toString, or nullStr if {@code null} input
294         * @since 2.0
295         */
296        public static String toString(Object obj) {
297            return obj == null ? "" : obj.toString();
298        }
299    
300        /**
301         * <p>Gets the {@code toString} of an {@code Object} returning
302         * a specified text if {@code null} input.</p>
303         *
304         * <pre>
305         * ObjectUtils.toString(null, null)           = null
306         * ObjectUtils.toString(null, "null")         = "null"
307         * ObjectUtils.toString("", "null")           = ""
308         * ObjectUtils.toString("bat", "null")        = "bat"
309         * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
310         * </pre>
311         *
312         * @see StringUtils#defaultString(String,String)
313         * @see String#valueOf(Object)
314         * @param obj  the Object to {@code toString}, may be null
315         * @param nullStr  the String to return if {@code null} input, may be null
316         * @return the passed in Object's toString, or nullStr if {@code null} input
317         * @since 2.0
318         */
319        public static String toString(Object obj, String nullStr) {
320            return obj == null ? nullStr : obj.toString();
321        }
322    
323        // Min/Max
324        //-----------------------------------------------------------------------
325        /**
326         * <p>Null safe comparison of Comparables.</p>
327         *
328         * @param <T> type of the values processed by this method
329         * @param values the set of comparable values, may be null
330         * @return
331         *  <ul>
332         *   <li>If any objects are non-null and unequal, the lesser object.
333         *   <li>If all objects are non-null and equal, the first.
334         *   <li>If any of the comparables are null, the lesser of the non-null objects.
335         *   <li>If all the comparables are null, null is returned.
336         *  </ul>
337         */
338        public static <T extends Comparable<? super T>> T min(T... values) {
339            T result = null;
340            if (values != null) {
341                for (T value : values) {
342                    if (compare(value, result, true) < 0) {
343                        result = value;
344                    }
345                }
346            }
347            return result;
348        }
349    
350        /**
351         * <p>Null safe comparison of Comparables.</p>
352         *
353         * @param <T> type of the values processed by this method
354         * @param values the set of comparable values, may be null
355         * @return
356         *  <ul>
357         *   <li>If any objects are non-null and unequal, the greater object.
358         *   <li>If all objects are non-null and equal, the first.
359         *   <li>If any of the comparables are null, the greater of the non-null objects.
360         *   <li>If all the comparables are null, null is returned.
361         *  </ul>
362         */
363        public static <T extends Comparable<? super T>> T max(T... values) {
364            T result = null;
365            if (values != null) {
366                for (T value : values) {
367                    if (compare(value, result, false) > 0) {
368                        result = value;
369                    }
370                }
371            }
372            return result;
373        }
374    
375        /**
376         * <p>Null safe comparison of Comparables.
377         * {@code null} is assumed to be less than a non-{@code null} value.</p>
378         *
379         * @param <T> type of the values processed by this method
380         * @param c1  the first comparable, may be null
381         * @param c2  the second comparable, may be null
382         * @return a negative value if c1 < c2, zero if c1 = c2
383         *  and a positive value if c1 > c2
384         */
385        public static <T extends Comparable<? super T>> int compare(T c1, T c2) {
386            return compare(c1, c2, false);
387        }
388    
389        /**
390         * <p>Null safe comparison of Comparables.</p>
391         *
392         * @param <T> type of the values processed by this method
393         * @param c1  the first comparable, may be null
394         * @param c2  the second comparable, may be null
395         * @param nullGreater if true {@code null} is considered greater
396         *  than a non-{@code null} value or if false {@code null} is
397         *  considered less than a Non-{@code null} value
398         * @return a negative value if c1 < c2, zero if c1 = c2
399         *  and a positive value if c1 > c2
400         * @see java.util.Comparator#compare(Object, Object)
401         */
402        public static <T extends Comparable<? super T>> int compare(T c1, T c2, boolean nullGreater) {
403            if (c1 == c2) {
404                return 0;
405            } else if (c1 == null) {
406                return (nullGreater ? 1 : -1);
407            } else if (c2 == null) {
408                return (nullGreater ? -1 : 1);
409            }
410            return c1.compareTo(c2);
411        }
412    
413        /**
414         * <p>Clone an object.</p>
415         *
416         * @param <T> the type of the object
417         * @param obj  the object to clone, null returns null
418         * @return the clone if the object implements {@link Cloneable} otherwise {@code null}
419         * @throws CloneFailedException if the object is cloneable and the clone operation fails
420         * @since 3.0
421         */
422        public static <T> T clone(final T obj) {
423            if (obj instanceof Cloneable) {
424                final Object result;
425                if (obj.getClass().isArray()) {
426                    final Class<?> componentType = obj.getClass().getComponentType();
427                    if (!componentType.isPrimitive()) {
428                        result = ((Object[]) obj).clone();
429                    } else {
430                        int length = Array.getLength(obj);
431                        result = Array.newInstance(componentType, length);
432                        while (length-- > 0) {
433                            Array.set(result, length, Array.get(obj, length));
434                        }
435                    }
436                } else {
437                    try {
438                        final Method clone = obj.getClass().getMethod("clone");
439                        result = clone.invoke(obj);
440                    } catch (final NoSuchMethodException e) {
441                        throw new CloneFailedException("Cloneable type "
442                            + obj.getClass().getName()
443                            + " has no clone method", e);
444                    } catch (final IllegalAccessException e) {
445                        throw new CloneFailedException("Cannot clone Cloneable type "
446                            + obj.getClass().getName(), e);
447                    } catch (final InvocationTargetException e) {
448                        throw new CloneFailedException("Exception cloning Cloneable type "
449                            + obj.getClass().getName(), e.getCause());
450                    }
451                }
452                @SuppressWarnings("unchecked")
453                final T checked = (T) result;
454                return checked;
455            }
456    
457            return null;
458        }
459    
460        /**
461         * <p>Clone an object if possible.</p>
462         *
463         * <p>This method is similar to {@link #clone(Object)}, but will return the provided
464         * instance as the return value instead of {@code null} if the instance
465         * is not cloneable. This is more convenient if the caller uses different
466         * implementations (e.g. of a service) and some of the implementations do not allow concurrent
467         * processing or have state. In such cases the implementation can simply provide a proper
468         * clone implementation and the caller's code does not have to change.</p>
469         *
470         * @param <T> the type of the object
471         * @param obj  the object to clone, null returns null
472         * @return the clone if the object implements {@link Cloneable} otherwise the object itself
473         * @throws CloneFailedException if the object is cloneable and the clone operation fails
474         * @since 3.0
475         */
476        public static <T> T cloneIfPossible(final T obj) {
477            final T clone = clone(obj);
478            return clone == null ? obj : clone;
479        }
480    
481        // Null
482        //-----------------------------------------------------------------------
483        /**
484         * <p>Class used as a null placeholder where {@code null}
485         * has another meaning.</p>
486         *
487         * <p>For example, in a {@code HashMap} the
488         * {@link java.util.HashMap#get(java.lang.Object)} method returns
489         * {@code null} if the {@code Map} contains {@code null} or if there is
490         * no matching key. The {@code Null} placeholder can be used to distinguish
491         * between these two cases.</p>
492         *
493         * <p>Another example is {@code Hashtable}, where {@code null}
494         * cannot be stored.</p>
495         */
496        public static class Null implements Serializable {
497            /**
498             * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0
499             *
500             * @see java.io.Serializable
501             */
502            private static final long serialVersionUID = 7092611880189329093L;
503    
504            /**
505             * Restricted constructor - singleton.
506             */
507            Null() {
508                super();
509            }
510    
511            /**
512             * <p>Ensure singleton.</p>
513             *
514             * @return the singleton value
515             */
516            private Object readResolve() {
517                return ObjectUtils.NULL;
518            }
519        }
520    
521    }