Class Utils
This class contains various static utility methods for working with collections, strings, objects, and other common operations.
Features:
- Collections: Array and list creation, conversion, and manipulation
- Strings: Formatting, comparison, and null-safe operations
- Objects: Equality checking, casting, and null handling
- Environment: System property and environment variable access
- Optionals: Enhanced Optional operations and conversions
See Also:
AssertionUtils- For argument validation and assertion methodsStringUtils- For additional string manipulation utilities- Overview > juneau-commons.utils
-
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedUtils()Constructor - This class is meant to be subclasses. -
Method Summary
Modifier and TypeMethodDescriptionstatic <T extends Number>
Tabs(T value) Returns the absolute value of the specified number.static booleanand(boolean... values) Returnstrue if all specified boolean values aretrue .static booleanShortcut for callingStringUtils.isBlank(CharSequence).static booleanConverts an object to a boolean.static <T> TCasts an object to a specific type if it's an instance of that type.static intCompares two objects for ordering.static StringShortcut for callingClassUtils.className(Object).static StringShortcut for callingClassUtils.classNameSimple(Object).static StringShortcut for callingClassUtils.classNameSimpleQualified(Object).static booleanTests if the string contains the specified substring.static <T> Tdef(T value, T defaultValue) Returns the specified value if not null, otherwise returns the default value.static booleane(CharSequence str) Checks if a string is empty (null or zero length).static booleanReturnstrue if the specified object is empty.static booleane(Collection<?> o) Checks if the specified collection isnull or empty.static booleanChecks if the specified map isnull or empty.static <T> T[]Creates an empty array of the specified type.static StringemptyIfNull(Object value) Returns the string representation of an object, or an empty string if the object isnull .static StringSettingLooks up a system property or environment variable.static <T> TLooks up a system property or environment variable, returning a default value if not found.static booleanTests two strings for equality, with optional case-insensitive matching.static <T> booleaneq(T o1, T o2) Tests two objects for equality, gracefully handling nulls and arrays.static <T,U> boolean eq(T o1, U o2, BiPredicate<T, U> test) Tests two objects for equality using a custom predicate, gracefully handling nulls.static booleanConvenience method for callingStringUtils.equalsIgnoreCase(Object, Object).static booleanConvenience method for callingStringUtils.equalsIgnoreCase(String, String).static booleanTests if the string ends with the specified suffix.static StringShortcut for callingStringUtils.format(String, Object...).static <T> TfirstNonNull(T... t) Returns the first non-null value in the specified array.Creates a formatted string supplier with format arguments for lazy evaluation.static <T extends Comparable<T>>
booleangt(T o1, T o2) Tests if the first object is greater than the second object.static <T extends Comparable<T>>
booleangte(T o1, T o2) Tests if the first object is greater than or equal to the second object.static final intCalculates a hash code for the specified values.static StringConverts the specified object into an identifiable string of the form "Class[identityHashCode]"static booleanChecks if the specified object is an array.static booleanisBetween(int n, int lower, int higher) Returnstrue if the specified number is inclusively between the two values.static booleanChecks if the specified Boolean is notnull and istrue .static StringConvenience method for callingStringUtils.lowerCase(String).static <T extends Comparable<T>>
booleanlt(T o1, T o2) Tests if the first object is less than the second object.static <T extends Comparable<T>>
booleanlte(T o1, T o2) Tests if the first object is less than or equal to the second object.static <T extends Comparable<T>>
Tmax(T o1, T o2) Returns the maximum of two comparable values.static <T> OptionalSupplier<T>Creates a thread-safe memoizing supplier that computes a value once and caches it.static <T> ResettableSupplier<T>Creates a resettable memoizing supplier that caches the result of the first call and optionally allows resetting.static <T extends Comparable<T>>
Tmin(T o1, T o2) Returns the minimum of two comparable values.static booleanReturnstrue if all specified values arenull .static <T> booleann(T value) Returnstrue if the specified object isnull .static booleanShortcut for callingStringUtils.isNotBlank(CharSequence).static booleanne(CharSequence o) Checks if the specified string is notnull and not empty.static booleanChecks if the specified object is notnull and not empty.static booleanne(Collection<?> value) Checks if the specified collection is notnull and not empty.static booleanChecks if the specified map is notnull and not empty.static <T> booleanneq(T s1, T s2) Null-safe not-equals check.static <T,U> boolean neq(T o1, U o2, BiPredicate<T, U> test) Tests two objects for inequality using a custom predicate, gracefully handling nulls.static booleanTests two strings for non-equality ignoring case, but gracefully handles nulls.static <T extends Number>
booleannm1(T value) Checks if the specified number is notnull and not-1 .static booleanReturnstrue if the specified object is notnull .static <T> TReturnsnull for the specified type.static booleannot(boolean value) Returns the logical negation of the specified boolean value.static StringnullIfEmpty(String value) Returns the specified string, ornull if that string isnull or empty.static <E> List<E>nullIfEmpty(List<E> val) Returnsnull if the specified list isnull or empty, otherwise returns the list.static <K,V> Map<K, V> nullIfEmpty(Map<K, V> val) Returnsnull if the specified map isnull or empty, otherwise returns the map.static <E> Set<E>nullIfEmpty(Set<E> val) Returnsnull if the specified set isnull or empty, otherwise returns the set.static final <T> Optional<T>opt(T t) Shortcut for callingOptional.ofNullable(Object).static final <T> Optional<T>opte()Returns an empty Optional.static booleanor(boolean... values) Returnstrue if any of the specified boolean values aretrue .static <T> Tor(T... t) Shortcut for callingfirstNonNull(Object...).static final voidprintLines(String[] lines) Prints all the specified lines to System.out with line numbers.static voidRuns a snippet of code and silently ignores any exceptions.static StringShortcut for callingStringUtils.readable(Object).static StringShortcut for converting an object to a string.static voidRuns a snippet of code and encapsulates any throwable inside aRuntimeException.static voidsafe(Snippet snippet, Function<Throwable, RuntimeException> exceptionMapper) Runs a snippet of code with a custom exception mapper.static <T> Tsafe(ThrowingSupplier<T> s) Used to wrap code that returns a value but throws an exception.static <T> Tsafe(ThrowingSupplier<T> s, Function<Exception, RuntimeException> exceptionMapper) Used to wrap code that returns a value but throws an exception, with a custom exception mapper.static <T> TsafeCatch(ThrowingSupplier<T> s, Function<Throwable, T> exceptionFunction) Executes a supplier that may throw an exception and returns the result or a fallback value.static <T> Optional<T>safeOpt(ThrowingSupplier<T> s) Executes a supplier that may throw an exception and returns an Optional.static <T> Optional<T>safeOptCatch(ThrowingSupplier<T> s, Function<Throwable, T> exceptionFunction) Executes a supplier that may throw an exception and returns an Optional with the result or a fallback value.static <T> TsafeOrNull(ThrowingSupplier<T> s) Executes a supplier that may throw an exception and returns the result ornull .static <T> TsafeSupplier(ThrowableUtils.SupplierWithThrowable<T> supplier) Allows you to wrap a supplier that throws an exception so that it can be used in a fluent interface.static <T> TsafeSupplier(ThrowableUtils.SupplierWithThrowable<T> supplier, Function<Throwable, RuntimeException> exceptionMapper) Allows you to wrap a supplier that throws an exception with a custom exception mapper.static StringBuilderHelper method for creating StringBuilder objects.Shortcut for callingStringUtils.stringSupplier(Supplier).static booleanTests if the string starts with the specified prefix.static StringShortcut for callingStringUtils.trim(String).static StringConvenience method for callingStringUtils.upperCase(String).static Object
-
Constructor Details
-
Utils
protected Utils()Constructor - This class is meant to be subclasses.
-
-
Method Details
-
bool
Converts an object to a boolean.- Parameters:
val- The object to convert.- Returns:
- The boolean value, or
false if the value wasnull .
-
cast
Casts an object to a specific type if it's an instance of that type.This is a null-safe and type-safe casting operation. Returns
null if:- The object is
null - The object is not an instance of the specified type
Behavior for incorrect instance types: If the object is not an instance of the specified type, this method returns
null rather than throwing aClassCastException. This makes it safe to use when you're unsure of the object's type and want to handle type mismatches gracefully.Example:
Object
obj ="Hello" ; Stringstr = cast(String.class ,obj );// "Hello" Integernum = cast(Integer.class ,obj );// null (not an Integer, no exception thrown) Stringstr2 = cast(String.class ,null );// null - Type Parameters:
T- The type to cast to.- Parameters:
c- The type to cast to.o- The object to cast.- Returns:
- The cast object, or
null if the object wasn't the specified type or wasnull .
- The object is
-
cn
Shortcut for callingClassUtils.className(Object).Returns the fully-qualified class name including the full package path.
Examples:
// Regular classes cn(String.class );// "java.lang.String" cn(new HashMap<>());// "java.util.HashMap" // Inner classes cn(Map.Entry.class );// "java.util.Map$Entry" // Primitives cn(int .class );// "int" cn(boolean .class );// "boolean" // Arrays cn(String[].class );// "[Ljava.lang.String;" cn(int [].class );// "[I" cn(String[][].class );// "[[Ljava.lang.String;" // Null cn(null );// null - Parameters:
value- The object to get the class name for.- Returns:
- The name of the class or
null if the value was null.
-
cns
Shortcut for callingClassUtils.classNameSimple(Object).Returns only the simple class name without any package or outer class information. For inner classes, only the innermost class name is returned.
Examples:
// Regular classes scn(String.class );// "String" scn(new HashMap<>());// "HashMap" // Inner classes scn(Map.Entry.class );// "Entry" // Primitives scn(int .class );// "int" scn(boolean .class );// "boolean" // Arrays scn(String[].class );// "String[]" scn(int [].class );// "int[]" scn(String[][].class );// "String[][]" // Null scn(null );// null - Parameters:
value- The object to get the simple class name for.- Returns:
- The simple name of the class or
null if the value was null.
-
cnsq
Shortcut for callingClassUtils.classNameSimpleQualified(Object).Returns the simple class name including outer class names, but without the package. Inner class separators ($) are replaced with dots (.). Array types are properly formatted with brackets.
Examples:
// Regular classes sqcn(String.class );// "String" sqcn(new HashMap<>());// "HashMap" // Inner classes sqcn(Map.Entry.class );// "Map.Entry" sqcn(Outer.Inner.Deep.class );// "Outer.Inner.Deep" // Primitives sqcn(int .class );// "int" sqcn(boolean .class );// "boolean" // Object arrays sqcn(String[].class );// "String[]" sqcn(Map.Entry[].class );// "Map.Entry[]" sqcn(String[][].class );// "String[][]" // Primitive arrays sqcn(int [].class );// "int[]" sqcn(boolean [][].class );// "boolean[][]" // Null sqcn(null );// null - Parameters:
value- The object to get the simple qualified class name for.- Returns:
- The simple qualified name of the class or
null if the value was null.
-
cmp
Compares two objects for ordering.This method attempts to compare two objects using their natural ordering if they implement
Comparableand are of the same type. Null handling:- Both
null → returns0 (equal) - First
null → returns-1 (null is less-than) - Second
null → returns1 (null is less-than) - Different types or not Comparable → returns
0 (cannot compare)
Example:
cmp(
"apple" ,"banana" );// negative (apple < banana) cmp(5, 10);// negative (5 < 10) cmp("apple" ,"apple" );// 0 (equal) cmp(null ,null );// 0 (equal) cmp(null ,"apple" );// -1 (null < non-null) cmp("apple" , 5);// 0 (different types, cannot compare) - Parameters:
o1- Object 1.o2- Object 2.- Returns:
-1 ,0 , or1 ifo1 is less-than, equal, or greater-thano2 . Returns0 if objects are not of the same type or do not implement theComparableinterface.
- Both
-
lt
Tests if the first object is less than the second object.Uses natural ordering if both objects implement
Comparableand are of the same type.Example:
lt(5, 10);
// true lt("apple" ,"banana" );// true lt(10, 5);// false lt(5, 5);// false - Type Parameters:
T- The object type.- Parameters:
o1- Object 1.o2- Object 2.- Returns:
true ifo1 is less thano2 .- See Also:
-
lte
Tests if the first object is less than or equal to the second object.Uses natural ordering if both objects implement
Comparableand are of the same type.Example:
lte(5, 10);
// true lte(5, 5);// true lte(10, 5);// false - Type Parameters:
T- The object type.- Parameters:
o1- Object 1.o2- Object 2.- Returns:
true ifo1 is less than or equal too2 .- See Also:
-
gt
Tests if the first object is greater than the second object.Uses natural ordering if both objects implement
Comparableand are of the same type.Example:
gt(10, 5);
// true gt("banana" ,"apple" );// true gt(5, 10);// false gt(5, 5);// false - Type Parameters:
T- The object type.- Parameters:
o1- Object 1.o2- Object 2.- Returns:
true ifo1 is greater thano2 .- See Also:
-
gte
Tests if the first object is greater than or equal to the second object.Uses natural ordering if both objects implement
Comparableand are of the same type.Example:
gte(10, 5);
// true gte(5, 5);// true gte(5, 10);// false - Type Parameters:
T- The object type.- Parameters:
o1- Object 1.o2- Object 2.- Returns:
true ifo1 is greater than or equal too2 .- See Also:
-
ea
Creates an empty array of the specified type.This is a convenience method for creating empty arrays using reflection. Useful when you need an empty array of a specific type but don't have an instance to call
new T[0] .Example:
String[]
empty = ea(String.class );// new String[0] Integer[]empty2 = ea(Integer.class );// new Integer[0] List<String>[]empty3 = ea(List.class );// new List[0] - Type Parameters:
T- The component type of the array.- Parameters:
type- The component type class.- Returns:
- An empty array of the specified type.
-
emptyIfNull
Returns the string representation of an object, or an empty string if the object isnull .This is a null-safe string conversion method. If the object is
null , returns an empty string. Otherwise, returns the result of callingObject.toString()on the object.Example:
emptyIfNull(
"Hello" );// "Hello" emptyIfNull(123);// "123" emptyIfNull(null );// "" - Parameters:
value- The value to convert to a string. Can benull .- Returns:
- The string representation of the value, or an empty string if
null . - See Also:
-
env
Looks up a system property or environment variable.This method searches for a value in the following order:
- System properties (via
System.getProperty(String)) - Environment variables (via
System.getenv(String)) - the name is converted to env-safe format
Returns an empty
Optionalif the value is not found in either location.Example:
// System property: -Dmy.property=value Optional<String>prop = env("my.property" );// Optional.of("value") // Environment variable: MY_PROPERTY=value Optional<String>env = env("my.property" );// Optional.of("value") (converts to MY_PROPERTY) Optional<String>missing = env("nonexistent" );// Optional.empty() - Parameters:
name- The property name (will be converted to env-safe format for environment variable lookup).- Returns:
- An
Optionalcontaining the value if found, or empty if not found. - See Also:
- System properties (via
-
env
Looks up a system property or environment variable, returning a default value if not found.This method searches for a value in the following order:
- System properties (via
System.getProperty(String)) - Environment variables (via
System.getenv(String)) - the name is converted to env-safe format - Returns the default value if not found
If a value is found, it is converted to the type of the default value using the Settings framework. Supported types include
Boolean,Charset, and other common types.Example:
// System property: -Dmy.property=true Booleanflag = env("my.property" ,false );// true // Environment variable: MY_PROPERTY=UTF-8 Charsetcharset = env("my.property" , Charset.defaultCharset());// UTF-8 // Not found, returns default Stringvalue = env("nonexistent" ,"default" );// "default" - Type Parameters:
T- The type to convert the value to.- Parameters:
name- The property name (will be converted to env-safe format for environment variable lookup).def- The default value to return if not found.- Returns:
- The found value (converted to type T), or the default value if not found.
- See Also:
- System properties (via
-
eq
Tests two strings for equality, with optional case-insensitive matching.This method provides a unified way to compare strings with or without case sensitivity. Both strings are handled gracefully for
null values.Example:
eq(
false ,"Hello" ,"Hello" );// true (case-sensitive) eq(false ,"Hello" ,"hello" );// false (case-sensitive) eq(true ,"Hello" ,"hello" );// true (case-insensitive) eq(false ,null ,null );// true (both null) eq(false ,"Hello" ,null );// false - Parameters:
caseInsensitive- Use case-insensitive matching.s1- String 1.s2- String 2.- Returns:
true if the strings are equal (according to the case sensitivity setting).- See Also:
-
eq
Tests two objects for equality, gracefully handling nulls and arrays.This method handles annotations specially by delegating to
AnnotationUtils.equals(java.lang.annotation.Annotation, java.lang.annotation.Annotation)to ensure proper annotation comparison according to the annotation equality contract.- Type Parameters:
T- The value types.- Parameters:
o1- Object 1.o2- Object 2.- Returns:
true if both objects are equal based on theObject.equals(Object)method.- See Also:
-
eq
Tests two objects for equality using a custom predicate, gracefully handling nulls.This method provides a convenient way to implement custom equality logic while handling null values safely. The predicate is only called if both objects are non-null and not the same reference.
Example:
// Custom equality for a Role class public boolean equals(Object o) {return eq(this , (Role)o, (x,y) -> eq(x.id, y.id) && eq(x.name, y.name) && eq(x.created, y.created) && eq(x.createdBy, y.createdBy) ); }// Usage Roler1 =new Role(1,"admin" ); Roler2 =new Role(1,"admin" ); eq(r1 ,r2 , (x,y) -> x.id == y.id && x.name.equals(y.name));// true - Type Parameters:
T- Object 1 type.U- Object 2 type.- Parameters:
o1- Object 1.o2- Object 2.test- The predicate to use for equality testing (only called if both objects are non-null and different references).- Returns:
true if both objects are equal based on the test, or if both arenull , or if they are the same reference.- See Also:
-
eqic
Convenience method for callingStringUtils.equalsIgnoreCase(Object, Object).Tests two objects for case-insensitive string equality by converting them to strings.
- Parameters:
o1- Object 1.o2- Object 2.- Returns:
true if both objects are equal ignoring case.
-
eqic
Convenience method for callingStringUtils.equalsIgnoreCase(String, String).Tests two strings for case-insensitive equality, but gracefully handles nulls.
- Parameters:
s1- String 1.s2- String 2.- Returns:
true if the strings are equal.
-
f
Shortcut for callingStringUtils.format(String, Object...).This method provides a convenient shorthand for string formatting that supports both MessageFormat-style and printf-style formatting in the same pattern.
Format Support:
- Printf-style:
"%s" ,"%d" ,"%.2f" ,"%1$s" , etc. - MessageFormat-style:
"{0}" ,"{1,number}" ,"{2,date}" , etc. - Un-numbered MessageFormat:
"{}" - Sequential placeholders that are automatically numbered - Mixed formats: Both styles can be used in the same pattern
Examples:
// Printf-style formatting f("Hello %s, you have %d items" ,"John" , 5);// Returns: "Hello John, you have 5 items" // Floating point f("Price: $%.2f" , 19.99);// Returns: "Price: $19.99" // MessageFormat-style formatting f("Hello {0}, you have {1} items" ,"John" , 5);// Returns: "Hello John, you have 5 items" // Un-numbered MessageFormat placeholders (sequential) f("Hello {}, you have {} items" ,"John" , 5);// Returns: "Hello John, you have 5 items" // Mixed format styles in the same pattern f("User {0} has %d items and %s status" ,"Alice" , 10,"active" );// Returns: "User Alice has 10 items and active status" - Parameters:
pattern- The format string supporting both MessageFormat and printf-style placeholders.args- The arguments to format.- Returns:
- The formatted string.
- See Also:
- Printf-style:
-
firstNonNull
Returns the first non-null value in the specified array.This method iterates through the provided values and returns the first one that is not
null . Useful for providing default values or selecting the first available option.Example:
firstNonNull(
null ,null ,"Hello" ,"World" );// "Hello" firstNonNull("Hello" ,"World" );// "Hello" firstNonNull(null ,null );// null firstNonNull();// null - Type Parameters:
T- The value types.- Parameters:
t- The values to check.- Returns:
- The first non-null value, or
null if the array is null or empty or contains onlynull values. - See Also:
-
or
Shortcut for callingfirstNonNull(Object...).Returns the first non-null value in the specified array.
Example:
or(
null ,null ,"Hello" ,"World" );// "Hello" or("Hello" ,"World" );// "Hello" or(null ,null );// null - Type Parameters:
T- The value types.- Parameters:
t- The values to check.- Returns:
- The first non-null value, or
null if all arenull . - See Also:
-
def
Returns the specified value if not null, otherwise returns the default value.This is a null-safe way to provide default values.
Example:
def(
"Hello" ,"World" );// "Hello" def(null ,"World" );// "World" - Type Parameters:
T- The value type.- Parameters:
value- The value to check.defaultValue- The default value to return ifvalue isnull .- Returns:
- The value if not null, otherwise the default value.
-
and
Returnstrue if all specified boolean values aretrue .Returns
true if the array is empty (vacuous truth).Example:
and(
true ,true ,true );// true and(true ,false ,true );// false and();// true (empty array) - Parameters:
values- The boolean values to test.- Returns:
true if all values aretrue .
-
or
Returnstrue if any of the specified boolean values aretrue .Returns
false if the array is empty.Example:
or(
true ,false ,false );// true or(false ,false ,false );// false or();// false (empty array) - Parameters:
values- The boolean values to test.- Returns:
true if any value istrue .
-
not
Returns the logical negation of the specified boolean value.Example:
not(
true );// false not(false );// true - Parameters:
value- The boolean value to negate.- Returns:
- The negated value.
-
min
Returns the minimum of two comparable values.Example:
min(5, 10);
// 5 min("apple" ,"banana" );// "apple" - Type Parameters:
T- The comparable type.- Parameters:
o1- Value 1.o2- Value 2.- Returns:
- The minimum value.
-
max
Returns the maximum of two comparable values.Example:
max(5, 10);
// 10 max("apple" ,"banana" );// "banana" - Type Parameters:
T- The comparable type.- Parameters:
o1- Value 1.o2- Value 2.- Returns:
- The maximum value.
-
abs
Returns the absolute value of the specified number.Example:
abs(-5);
// 5 abs(5);// 5 abs(-3.14);// 3.14 - Type Parameters:
T- The number type.- Parameters:
value- The number.- Returns:
- The absolute value.
-
fs
Creates a formatted string supplier with format arguments for lazy evaluation.This method returns a
Supplierthat formats the string pattern with the provided arguments only when the supplier'sget()method is called. This is useful for expensive string formatting operations that may not always be needed, such as error messages in assertions.Supports both MessageFormat-style and printf-style formatting in the same pattern. Also supports un-numbered MessageFormat placeholders:
"{}" - Sequential placeholders that are automatically numbered. Seef(String, Object...)for format specification details.Usage Examples:
// Lazy evaluation - string is only formatted if assertion fails assertTrue(condition, fs("Expected %s but got %s" , expected, actual));// Can be used anywhere a Supplier<String> is expected Supplier<String>messageSupplier = fs("Processing item %d of %d" , i, total);// Mixed format styles Supplier<String>msg = fs("User {0} has %d items" ,"Alice" , 10);// Un-numbered MessageFormat placeholders Supplier<String>msg2 = fs("Hello {}, you have {} items" ,"John" , 5);- Parameters:
pattern- The format string supporting both MessageFormat and printf-style placeholders (e.g.,"{0}" ,"%s" ,"%d" , etc.).args- The arguments to substitute into the pattern placeholders.- Returns:
- A
Supplierthat will format the string whenget()is called. - See Also:
-
h
Calculates a hash code for the specified values.This method delegates to
HashCode.of(Object...)to combine multiple values into a single hash code. It uses the same algorithm asObjects.hash(Object...)(31 * result + element hash).Special handling is provided for:
- Annotations: Uses
AnnotationUtils.hash(java.lang.annotation.Annotation)to ensure consistent hashing according to theAnnotation.hashCode()contract. - Arrays: Uses content-based hashing via
Arrays.hashCode(Object[])instead of identity-based hashing. - Null values: Treated as 0 in the hash calculation.
Example:
// Hash multiple values int hash1 = h("Hello" , 123,true );// Hash with annotations int hash2 = h(myAnnotation ,"value" );// Hash with arrays (content-based) int hash3 = h(new int []{1, 2, 3});// Use in hashCode() implementation public int hashCode() {return h(id, name, created); }- Parameters:
values- The values to hash.- Returns:
- A hash code value for the given values.
- See Also:
- Annotations: Uses
-
id
Converts the specified object into an identifiable string of the form "Class[identityHashCode]"- Parameters:
o- The object to convert to a string.- Returns:
- An identity string.
-
isArray
Checks if the specified object is an array.This method checks if the object is not
null and its class represents an array type (primitive arrays or object arrays).Example:
isArray(
new int []{1, 2, 3});// true isArray(new String[]{"a", "b"});// true isArray("Hello" );// false isArray(null );// false - Parameters:
o- The object to check.- Returns:
true if the object is notnull and is an array.- See Also:
-
isBetween
Returnstrue if the specified number is inclusively between the two values.- Parameters:
n- The number to check.lower- The lower bound (inclusive).higher- The upper bound (inclusive).- Returns:
true if the number is between the bounds.
-
e
Checks if a string is empty (null or zero length).Example:
e(
null );// true e("" );// true e(" " );// false e("hello" );// false - Parameters:
str- The string to check.- Returns:
true if the string is null or has zero length.
-
e
Checks if the specified collection isnull or empty.This is a null-safe operation. Returns
true if the collection isnull or has no elements.Example:
e(
null );// true e(Collections.emptyList());// true e(Arrays.asList(1, 2, 3));// false - Parameters:
o- The collection to check.- Returns:
true if the specified collection isnull or empty.- See Also:
-
e
Checks if the specified map isnull or empty.This is a null-safe operation. Returns
true if the map isnull or has no key-value mappings.Example:
e(
null );// true e(Collections.emptyMap());// true e(Map.of("key" ,"value" ));// false - Parameters:
o- The map to check.- Returns:
true if the specified map isnull or empty.- See Also:
-
e
Returnstrue if the specified object is empty.Return
true if the value is any of the following:null - An empty Collection
- An empty Map
- An empty array
- An empty CharSequence
- An empty String when serialized to a string using
Object.toString().
- Parameters:
o- The object to test.- Returns:
true if the specified object is empty.
-
ne
Checks if the specified string is notnull and not empty.This is the inverse of
e(CharSequence). Note: This method does not check for blank strings (whitespace-only strings).Example:
ne(
"Hello" );// true ne(" " );// true (whitespace is not empty) ne(null );// false ne("" );// false - Parameters:
o- The string to check.- Returns:
true if string is notnull and not empty.- See Also:
-
ne
Checks if the specified collection is notnull and not empty.This is the inverse of
e(Collection).Example:
ne(Arrays.asList(1, 2, 3));
// true ne(null );// false ne(Collections.emptyList());// false - Parameters:
value- The collection to check.- Returns:
true if the specified collection is notnull and not empty.- See Also:
-
ne
Checks if the specified map is notnull and not empty.This is the inverse of
e(Map).Example:
ne(Map.of(
"key" ,"value" ));// true ne(null );// false ne(Collections.emptyMap());// false - Parameters:
value- The map to check.- Returns:
true if the specified map is notnull and not empty.- See Also:
-
ne
Checks if the specified object is notnull and not empty.This method works on any of the following data types:
- String, CharSequence - checks if length > 0
- Collection - checks if not empty
- Map - checks if not empty
- Array - checks if length > 0
- All other types - converts to string and checks if not empty
Example:
ne(
"Hello" );// true ne(Arrays.asList(1, 2));// true ne(Map.of("key" ,"value" ));// true ne(null );// false ne("" );// false ne(Collections.emptyList());// false - Parameters:
value- The value being checked.- Returns:
true if the specified object is notnull and not empty.- See Also:
-
nm1
Checks if the specified number is notnull and not-1 .This method is commonly used to check if a numeric value represents a valid index or ID, where
-1 is often used as a sentinel value to indicate "not found" or "invalid".Example:
nm1(5);
// true nm1(0);// true nm1(-1);// false nm1(null );// false - Type Parameters:
T- The value types.- Parameters:
value- The value being checked.- Returns:
true if the specified number is notnull and not-1 .
-
n
Returnstrue if the specified object isnull .Equivalent to
, but with a more readable method name.value ==null Example:
n(
null );// true n("Hello" );// false n(123);// false - Type Parameters:
T- The object type.- Parameters:
value- The object to check.- Returns:
true if the specified object isnull .- See Also:
-
n
Returnstrue if all specified values arenull .If the values array itself is
null , returnstrue . If any value in the array is notnull , returnsfalse .Example:
boolean allNull =n (null ,null ,null );// true boolean notAllNull =n (null ,"value" ,null );// false - Parameters:
values- The values to check.- Returns:
true if all values arenull (or the array isnull ),false otherwise.
-
isTrue
Checks if the specified Boolean is notnull and istrue .This is a null-safe way to check if a Boolean wrapper is true. Returns
false if the value isnull orfalse .Example:
isTrue(
true );// true isTrue(false );// false isTrue(null );// false - Parameters:
value- The value being checked.- Returns:
true if the specified boolean is notnull and istrue .
-
lc
Convenience method for callingStringUtils.lowerCase(String).Converts the string to lowercase if not null.
- Parameters:
value- The string to convert.- Returns:
- The lowercase string, or
null if the input wasnull .
-
mem
Creates a thread-safe memoizing supplier that computes a value once and caches it.The returned supplier is thread-safe and guarantees that the underlying supplier's
get()method is called at most once, even under concurrent access. The computed value is cached and returned on all subsequent calls.This is useful for lazy initialization of expensive-to-compute values that should only be calculated once.
Example:
// Create a memoizing supplier Supplier<ExpensiveObject>supplier = mem(() ->new ExpensiveObject());// First call computes and caches the value ExpensiveObjectobj1 =supplier .get();// Subsequent calls return the cached value (no recomputation) ExpensiveObjectobj2 =supplier .get();// Same instance as obj1 Thread Safety:
The implementation uses
AtomicReferencewith double-checked locking to ensure thread-safe lazy initialization. Under high contention, multiple threads may compute the value, but only one result is stored and returned to all callers.Notes:
- The supplier may be called multiple times if threads race, but only one result is cached.
- The cached value can be
null if the supplier returnsnull . - Once cached, the value never changes (immutable after first computation).
- The returned supplier does not support
Object.toString(),Object.equals(Object), orObject.hashCode().
- Type Parameters:
T- The type of value supplied.- Parameters:
supplier- The supplier to memoize. Must not benull .- Returns:
- A thread-safe memoizing wrapper around the supplier.
- Throws:
NullPointerException- if supplier isnull .
-
memr
Creates a resettable memoizing supplier that caches the result of the first call and optionally allows resetting.This is similar to
mem(Supplier), but returns aResettableSupplierthat supports clearing the cached value, forcing recomputation on the next call.Usage:
ResettableSupplier<String>
supplier = Utils.memr (() -> expensiveComputation());// First call computes and caches Stringresult1 =supplier .get();// Subsequent calls return cached value Stringresult2 =supplier .get();// Reset forces recomputation on next get() supplier .reset(); Stringresult3 =supplier .get();// Recomputes Thread Safety:
The returned supplier is thread-safe for both
ResettableSupplier.get()andResettableSupplier.reset()operations. If multiple threads call get() simultaneously after a reset, the supplier may be invoked multiple times, but only one result will be cached.See Also:
- Type Parameters:
T- The type of value supplied.- Parameters:
supplier- The supplier to memoize. Must not benull .- Returns:
- A thread-safe resettable memoizing wrapper around the supplier.
- Throws:
NullPointerException- if supplier isnull .
-
no
Returnsnull for the specified type.This is a convenience method that allows you to explicitly return
null with a type parameter, which can help with type inference in some contexts.Example:
String
result = n(String.class );// null List<String>list = n(List.class );// null - Type Parameters:
T- The type.- Parameters:
type- The type class (unused, but helps with type inference).- Returns:
null .
-
neq
Null-safe not-equals check.This is the inverse of
eq(Object, Object). Returnstrue if the objects are not equal, handlingnull values gracefully.Example:
ne(
"Hello" ,"World" );// true ne("Hello" ,"Hello" );// false ne(null ,null );// false ne("Hello" ,null );// true - Type Parameters:
T- The object type.- Parameters:
s1- Object 1.s2- Object 2.- Returns:
true if the objects are not equal.- See Also:
-
neq
Tests two objects for inequality using a custom predicate, gracefully handling nulls.This is the inverse of
eq(Object, Object, BiPredicate). The predicate is only called if both objects are non-null and not the same reference.Example:
Role
r1 =new Role(1,"admin" ); Roler2 =new Role(2,"user" ); ne(r1 ,r2 , (x,y) -> x.id == y.id);// true (different IDs) - Type Parameters:
T- Object 1 type.U- Object 2 type.- Parameters:
o1- Object 1.o2- Object 2.test- The predicate to use for equality testing (only called if both objects are non-null and different references).- Returns:
true if the objects are not equal based on the test, or if one isnull and the other is not.- See Also:
-
neqic
Tests two strings for non-equality ignoring case, but gracefully handles nulls.This is the inverse of
eqic(String, String).Example:
neic(
"Hello" ,"World" );// true neic("Hello" ,"hello" );// false (equal ignoring case) neic(null ,null );// false (both null) neic("Hello" ,null );// true - Parameters:
s1- String 1.s2- String 2.- Returns:
true if the strings are not equal ignoring case.- See Also:
-
nn
Returnstrue if the specified object is notnull .Equivalent to
, but with a more readable method name.o !=null Example:
import static org.apache.juneau.commons.utils.Utils.*;if (nn (myObject )) {// Do something with non-null object }- Parameters:
o- The object to check.- Returns:
true if the specified object is notnull .
-
opt
Shortcut for callingOptional.ofNullable(Object).This is a convenience method that provides a shorter name for wrapping objects in an Optional.
Example:
Optional<String>
opt1 = opt("Hello" );// Optional.of("Hello") Optional<String>opt2 = opt(null );// Optional.empty() - Type Parameters:
T- The object type.- Parameters:
t- The object to wrap in an Optional.- Returns:
- An Optional containing the specified object, or empty if
null . - See Also:
-
opte
Returns an empty Optional.This is a convenience method that provides a shorter name for creating an empty Optional.
Example:
Optional<String>
empty = opte();// Optional.empty() - Type Parameters:
T- The object type.- Returns:
- An empty Optional.
- See Also:
-
printLines
Prints all the specified lines to System.out with line numbers.Each line is printed with a 4-digit line number prefix (e.g., " 1:", " 2:", etc.). This is useful for debugging or displaying formatted output.
Example:
printLines(
new String[]{"First line" ,"Second line" });// Output: // 1:First line // 2:Second line - Parameters:
lines- The lines to print.
-
r
Shortcut for callingStringUtils.readable(Object).Converts an arbitrary object to a readable string format suitable for debugging and testing.
- Parameters:
o- The object to convert to readable format. Can benull .- Returns:
- A readable string representation of the object, or
null if the input wasnull . - See Also:
-
s
Shortcut for converting an object to a string.This is a null-safe string conversion. Returns
null if the object isnull , otherwise returns the result of callingObject.toString()on the object.Example:
s(
"Hello" );// "Hello" s(123);// "123" s(null );// null - Parameters:
val- The object to convert.- Returns:
- The string representation of the object, or
null if the object isnull . - See Also:
-
safe
Runs a snippet of code and encapsulates any throwable inside aRuntimeException.- Parameters:
snippet- The snippet of code to run.
-
quiet
Runs a snippet of code and silently ignores any exceptions.This method is useful for operations that may fail but where you want to handle the failure gracefully by ignoring it. This is commonly used for "quietly" closing resources where exceptions during close operations are not critical.
Example:
// Quietly close a stream, ignoring any exceptions Utils.quiet (() -> stream.close());This is different from
safe(Snippet)which wraps exceptions in aRuntimeException.- Parameters:
snippet- The snippet of code to run.- See Also:
-
safe
Runs a snippet of code with a custom exception mapper.This method allows you to define a function that converts any thrown throwable into a runtime exception. This is useful when you need to wrap exceptions in a specific runtime exception type.
Example:
// Wrap code execution with custom exception handling Utils.safe (() -> {// some code that may throw },e ->new CustomRuntimeException(e ));- Parameters:
snippet- The snippet of code to run.exceptionMapper- A function that converts the thrown throwable into a runtime exception.- Throws:
RuntimeException- The exception returned by the exception mapper if the snippet throws a throwable.
-
safe
Used to wrap code that returns a value but throws an exception. Useful in cases where you're trying to execute code in a fluent method call or are trying to eliminate untestable catch blocks in code.- Type Parameters:
T- The return type.- Parameters:
s- The supplier that may throw an exception.- Returns:
- The result of the supplier execution.
-
safe
public static <T> T safe(ThrowingSupplier<T> s, Function<Exception, RuntimeException> exceptionMapper) Used to wrap code that returns a value but throws an exception, with a custom exception mapper.This method allows you to define a function that converts any thrown exception into a runtime exception. This is useful when you need to wrap exceptions in a specific runtime exception type (e.g.,
ExecutableException).Example:
// Wrap a constructor invocation with custom exception handling return Utils.safe (() -> {try {return (T )inner.newInstance(args); }catch (InvocationTargetExceptione ) {throw new ExecutableException(e .getTargetException()); } },e ->new ExecutableException(e ));- Type Parameters:
T- The return type.- Parameters:
s- The supplier that may throw an exception.exceptionMapper- A function that converts the thrown exception into a runtime exception.- Returns:
- The result of the supplier execution.
- Throws:
RuntimeException- The exception returned by the exception mapper if the supplier throws an exception.
-
safeCatch
Executes a supplier that may throw an exception and returns the result or a fallback value.If the supplier executes successfully, returns the result. If the supplier throws any exception, applies the exception function to get a fallback value.
This is useful for operations that may fail but you want to handle the failure gracefully by returning a fallback value instead of throwing an exception.
Example:
// Get a value with a fallback if an exception occurs String value =safeCatch (() ->riskyOperation (),e ->"default" );- Type Parameters:
T- The return type.- Parameters:
s- The supplier that may throw an exception.exceptionFunction- A function that converts the thrown exception into a fallback value.- Returns:
- The result of the supplier execution, or the fallback value if an exception was thrown.
- See Also:
-
safeOpt
Executes a supplier that may throw an exception and returns an Optional.If the supplier executes successfully, returns
Optional.of(Object)with the result. If the supplier throws any exception, returnsOptional.empty().This is useful for operations that may fail but you want to handle the failure gracefully by returning an empty Optional instead of throwing an exception.
Example:
// Check if AccessibleObject.isAccessible() method exists (Java 9+) boolean isAccessible =safeOpt (() -> (boolean )AccessibleObject.class .getMethod("isAccessible" ).invoke(obj ) ).orElse(false );- Type Parameters:
T- The return type.- Parameters:
s- The supplier that may throw an exception.- Returns:
- An Optional containing the result if successful, or empty if an exception was thrown.
- See Also:
-
safeOptCatch
public static <T> Optional<T> safeOptCatch(ThrowingSupplier<T> s, Function<Throwable, T> exceptionFunction) Executes a supplier that may throw an exception and returns an Optional with the result or a fallback value.If the supplier executes successfully, returns
Optional.of(Object)with the result. If the supplier throws any exception, applies the exception function to get a fallback value and returns it wrapped in an Optional.This is useful for operations that may fail but you want to handle the failure gracefully by returning a fallback value wrapped in an Optional instead of throwing an exception.
Example:
// Get a value with a fallback if an exception occurs Optional <String >value =safeOptCatch (() ->riskyOperation (),e ->"default" );- Type Parameters:
T- The return type.- Parameters:
s- The supplier that may throw an exception.exceptionFunction- A function that converts the thrown exception into a fallback value.- Returns:
- An Optional containing the result if successful, or the fallback value wrapped in an Optional if an exception was thrown.
- See Also:
-
safeOrNull
Executes a supplier that may throw an exception and returns the result ornull .If the supplier executes successfully, returns the result. If the supplier throws any exception, returns
null .This is useful for operations that may fail but you want to handle the failure gracefully by returning
null instead of throwing an exception. This is particularly useful in fluent method chains where you want to filter out failed conversions.This method is similar to
safeOpt(ThrowingSupplier)but returnsnull instead ofOptional.empty() when an exception occurs. Use this method when you prefernull overOptional for error handling.Example:
// Parse an integer, returning null if parsing fails Integervalue =safeOrNull (() -> Integer.valueOf("123" ));// 123 Integerinvalid =safeOrNull (() -> Integer.valueOf("abc" ));// null // Use in a fluent chain to filter out failed conversions Optional<Integer>parsed = get("my.property" ) .map(v ->safeOrNull (() -> Integer.valueOf(v ))) .filter(Objects::nonNull);- Type Parameters:
T- The return type.- Parameters:
s- The supplier that may throw an exception.- Returns:
- The result of the supplier if successful, or
null if an exception was thrown. - See Also:
-
safeSupplier
Allows you to wrap a supplier that throws an exception so that it can be used in a fluent interface.- Type Parameters:
T- The supplier type.- Parameters:
supplier- The supplier throwing an exception.- Returns:
- The supplied result.
- Throws:
RuntimeException- if supplier threw an exception.
-
safeSupplier
public static <T> T safeSupplier(ThrowableUtils.SupplierWithThrowable<T> supplier, Function<Throwable, RuntimeException> exceptionMapper) Allows you to wrap a supplier that throws an exception with a custom exception mapper.This method allows you to define a function that converts any thrown throwable into a runtime exception. This is useful when you need to wrap exceptions in a specific runtime exception type.
Example:
// Wrap a supplier with custom exception handling return Utils.safeSupplier (() -> {// some code that may throw return result ; },e ->new CustomRuntimeException(e ));- Type Parameters:
T- The supplier type.- Parameters:
supplier- The supplier throwing an exception.exceptionMapper- A function that converts the thrown throwable into a runtime exception.- Returns:
- The supplied result.
- Throws:
RuntimeException- The exception returned by the exception mapper if the supplier threw a throwable.
-
sb
Helper method for creating StringBuilder objects.- Parameters:
value- The string value to wrap in a StringBuilder.- Returns:
- A new StringBuilder containing the specified value.
-
ss
Shortcut for callingStringUtils.stringSupplier(Supplier).- Parameters:
s- The supplier.- Returns:
- A string supplier that calls
r(Object)on the supplied value.
-
uc
Convenience method for callingStringUtils.upperCase(String).Converts the string to uppercase if not null.
- Parameters:
value- The string to convert.- Returns:
- The uppercase string, or
null if the input wasnull .
-
b
Shortcut for callingStringUtils.isBlank(CharSequence).Returns
true if the string is blank (null, empty, or whitespace only).Example:
b(
null );// true b("" );// true b(" " );// true b("hello" );// false - Parameters:
str- The string to check.- Returns:
true if the string is blank.- See Also:
-
nb
Shortcut for callingStringUtils.isNotBlank(CharSequence).Returns
true if the string is not blank (not null, not empty, and contains non-whitespace).Example:
nb(
"hello" );// true nb(null );// false nb("" );// false nb(" " );// false - Parameters:
str- The string to check.- Returns:
true if the string is not blank.- See Also:
-
tr
Shortcut for callingStringUtils.trim(String).Trims whitespace from both ends of the string.
Example:
tr(
" hello " );// "hello" tr("hello" );// "hello" tr(null );// null - Parameters:
str- The string to trim.- Returns:
- The trimmed string, or
null if the input wasnull . - See Also:
-
sw
Tests if the string starts with the specified prefix.Null-safe operation. Returns
false if either string isnull .Example:
sw(
"hello" ,"he" );// true sw("hello" ,"lo" );// false sw(null ,"he" );// false - Parameters:
str- The string to test.prefix- The prefix to test for.- Returns:
true if the string starts with the prefix.
-
ew
Tests if the string ends with the specified suffix.Null-safe operation. Returns
false if either string isnull .Example:
ew(
"hello" ,"lo" );// true ew("hello" ,"he" );// false ew(null ,"lo" );// false - Parameters:
str- The string to test.suffix- The suffix to test for.- Returns:
true if the string ends with the suffix.
-
co
Tests if the string contains the specified substring.Null-safe operation. Returns
false if either string isnull .Example:
co(
"hello" ,"ell" );// true co("hello" ,"xyz" );// false co(null ,"ell" );// false - Parameters:
str- The string to test.substring- The substring to search for.- Returns:
true if the string contains the substring.
-
unwrap
- Parameters:
o- The object to unwrap.- Returns:
- The unwrapped object.
-
nullIfEmpty
Returns the specified string, ornull if that string isnull or empty.- Parameters:
value- The string value to check.- Returns:
- The string value, or
null if the string isnull or empty.
-
nullIfEmpty
Returnsnull if the specified map isnull or empty, otherwise returns the map.This is a convenience method for preserving backward compatibility when maps are initialized immediately but getters should return
null if the map is empty.- Type Parameters:
K- The key type.V- The value type.- Parameters:
val- The map to check.- Returns:
null if the map isnull or empty, otherwise the map itself.
-
nullIfEmpty
Returnsnull if the specified list isnull or empty, otherwise returns the list.This is a convenience method for preserving backward compatibility when lists are initialized immediately but getters should return
null if the list is empty.- Type Parameters:
E- The element type.- Parameters:
val- The list to check.- Returns:
null if the list isnull or empty, otherwise the list itself.
-
nullIfEmpty
Returnsnull if the specified set isnull or empty, otherwise returns the set.This is a convenience method for preserving backward compatibility when sets are initialized immediately but getters should return
null if the set is empty.- Type Parameters:
E- The element type.- Parameters:
val- The set to check.- Returns:
null if the set isnull or empty, otherwise the set itself.
-