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