Package io.microsphere.util
Class ObjectUtils
- java.lang.Object
-
- io.microsphere.util.ObjectUtils
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static <T> TdefaultIfNull(T object, java.util.function.Supplier<T> defaultValueSupplier)Returns the given object if it is non-null, otherwise returns the default value supplied by theSupplier.static <T> TdefaultIfNull(T object, T defaultValue)Returns the given object if it is non-null, otherwise returns the default value.static <S,T>
TnullSafe(S source, java.util.function.Function<S,T> function)Applies the given function to the source object if it is non-null, otherwise returns null.
-
-
-
Method Detail
-
nullSafe
@Nullable public static <S,T> T nullSafe(@Nullable S source, java.util.function.Function<S,T> function)Applies the given function to the source object if it is non-null, otherwise returns null. This method helps to avoid NullPointerException when chaining operations on potentially null objects.Example Usage
String name = ObjectUtils.nullSafe(user, User::getName); // returns user.getName() if user is not null, otherwise null Integer length = ObjectUtils.nullSafe(name, String::length); // returns name.length() if name is not null, otherwise null- Type Parameters:
S- the type of the source objectT- the type of the result- Parameters:
source- the source object to apply the function tofunction- the function to apply to the source object- Returns:
- the result of applying the function to the source object, or null if the source object is null
-
defaultIfNull
public static <T> T defaultIfNull(@Nullable T object, java.util.function.Supplier<T> defaultValueSupplier)Returns the given object if it is non-null, otherwise returns the default value supplied by theSupplier.Example Usage
String result = ObjectUtils.defaultIfNull(null, () -> "default"); // returns "default" String result2 = ObjectUtils.defaultIfNull("value", () -> "default"); // returns "value"- Type Parameters:
T- the type of the object- Parameters:
object- the object to checkdefaultValueSupplier- the supplier of the default value to return if the object is null- Returns:
- the object if non-null, otherwise the value provided by the supplier
-
defaultIfNull
@Nullable public static <T> T defaultIfNull(@Nullable T object, @Nullable T defaultValue)Returns the given object if it is non-null, otherwise returns the default value.Example Usage
String result = ObjectUtils.defaultIfNull(null, "default"); // returns "default" String result2 = ObjectUtils.defaultIfNull("value", "default"); // returns "value"The source from org.apache.commons.lang3.ObjectUtils#defaultIfNull(Object, Object)
- Type Parameters:
T- the type of the object- Parameters:
object- the object to checkdefaultValue- the default value to return if the object is null- Returns:
- the object if non-null, otherwise the default value
-
-