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