Class Utils
- Direct Known Subclasses:
Utils2
This class contains various static utility methods for working with collections, strings, objects, and other common operations.
-
Constructor Summary
ConstructorsModifierConstructorDescriptionprotected
Utils()
Constructor - This class is meant to be subclasses. -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> T[]
a
(T... x) Creates an array of objects.static <T> List<T>
accumulate
(Object o) Traverses all elements in the specified object and accumulates them into a list.static <T> List<T>
alist
(T... values) Shortcut for creating an unmodifiable list out of an array of values.static <E> E[]
array
(Collection<E> value, Class<E> componentType) Converts the specified collection to an array.arrayToList
(Object array) Converts any array (including primitive arrays) to a List.static final void
Throws anIllegalArgumentException
if the specified expression isfalse .static final <T> T
assertArgNotNull
(String name, T o) Throws anIllegalArgumentException
if the specified argument isnull .static final String
assertArgNotNullOrBlank
(String name, String o) Throws anIllegalArgumentException
if the specified string isnull or blank.static final <E> Class<E>[]
assertClassArrayArgIsType
(String name, Class<E> type, Class<?>[] value) Throws anIllegalArgumentException
if the specified value doesn't have all subclasses of the specified type.static final <T> T[]
assertVarargsNotNull
(String name, T[] o) Throws anIllegalArgumentException
if the specified varargs array or any of its elements arenull .static <T> T
Casts an object to a specific type if it's an instance of that type.static <T> T
castOrNull
(Object o, Class<T> c) If the specified object is an instance of the specified class, casts it to that type.static String
Gets the fully qualified class name of the specified object.static int
Compares two objects for equality.static boolean
Null-safeString.contains(CharSequence)
operation.static boolean
Null-safeString.contains(CharSequence)
operation.static <T> T[]
Creates an empty array of the specified type.static <T> List<T>
Shortcut for creating an empty list of the specified type.static <K,
V> Map<K, V> Shortcut for creating an empty map of the specified types.static <T> Optional<T>
empty()
Returns an emptyOptional
.static String
emptyIfNull
(Object value) Returns the specified string, or blank if that string is null.Looks up a system property or environment variable.static <T> T
Looks up a system property or environment variable.static boolean
Tests two strings for equality, but gracefully handles nulls.static <T> boolean
eq
(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, gracefully handling nulls.static boolean
Tests two strings for case-insensitive equality, but gracefully handles nulls.static String
Same as MessageFormat.format().static <T> T
firstNonNull
(T... t) Returns the first non-null value in the specified arrayCreates a formatted string supplier with message arguments for lazy evaluation.static Pattern
Converts a string containing"*" meta characters with a regular expression pattern.static Pattern
getMatchPattern3
(String s, int flags) Converts a string containing"*" meta characters with a regular expression pattern.static final int
Shortcut for callingObjects.hash(Object...)
.static IllegalArgumentException
illegalArg
(String msg, Object... args) Creates anIllegalArgumentException
.static boolean
Checks if the specified object is an array.static boolean
static boolean
Returnstrue if the specified object is empty.static boolean
Returnstrue if string isnull or empty.static boolean
Returnstrue if specified string isnull or empty or consists of only blanks.static boolean
isNotEmpty
(Object value) Returnstrue if the specified object is notnull and not empty.static boolean
isNotEmpty
(String o) Returnstrue if string is notnull and not empty.static <T extends Number>
booleanisNotMinusOne
(T value) Returnstrue if the specified number is notnull and not-1 .static <T> boolean
isNotNull
(T value) Returnstrue if the specified object is notnull .static boolean
Returnstrue if the specified boolean is notnull and istrue .static String
join
(int[] tokens, char d) Join the specified tokens into a delimited string.static String
Joins the specified tokens into a delimited string.static StringBuilder
join
(Object[] tokens, char d, StringBuilder sb) Join the specified tokens into a delimited string and writes the output to the specified string builder.static String
Join the specified tokens into a delimited string.static String
join
(Collection<?> tokens, char d) Join the specified tokens into a delimited string.static String
join
(Collection<?> tokens, String d) Join the specified tokens into a delimited string.static StringBuilder
join
(Collection<?> tokens, String d, StringBuilder sb) Joins the specified tokens into a delimited string and writes the output to the specified string builder.static String
Join the specified tokens into a delimited string.static String
Join the specified tokens into a delimited string.static StringBuilder
join
(List<?> tokens, String d, StringBuilder sb) Joins the specified tokens into a delimited string and writes the output to the specified string builder.static String
Joins tokens with newlines.static <T> List<T>
list
(T... values) Shortcut for creating a modifiable list out of an array of values.static <E> ArrayList<E>
listOfSize
(int size) Convenience method for creating anArrayList
of the specified size.static <K,
V> LinkedHashMap<K, V> Shortcut for creating a modifiable map out of an array of key-value pairs.static <T> T
Returnsnull for the specified type.static <T> T[]
Returnsnull for the specified array type.static <T> boolean
ne
(T s1, T s2) Null-safe not-equals check.static <T,
U> boolean ne
(T o1, U o2, BiPredicate<T, U> test) Tests two objects for inequality, gracefully handling nulls.static boolean
Tests two strings for non-equality ignoring case, but gracefully handles nulls.static <T> List<T>
Returns a null list.static <K,
V> Map<K, V> Returns a null map.static boolean
notContains
(String s, char... values) Null-safe string not-contains operation.static String
nullIfEmpty
(String value) Returns the specified string, ornull if that string isnull or empty.static String
Returnsnull if the specified string isnull or empty.static String
Returns an obfuscated version of the specified string.static final <T> Optional<T>
opt
(T t) Shortcut for callingOptional.ofNullable(Object)
.static final <T> Optional<T>
opte()
Returns an empty Optional.static final void
printLines
(String[] lines) Prints all the specified lines to System.out.static String
Converts an arbitrary object to a readable string format suitable for debugging and testing.static RuntimeException
runtimeException
(String msg, Object... args) Creates aRuntimeException
.static String
Shortcut for converting an object to a string.static void
Runs a snippet of code and encapsulates any throwable inside aRuntimeException
.static <T> T
safe
(ThrowingSupplier<T> s) Used to wrap code that returns a value but throws an exception.static <T> T
safeSupplier
(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 StringBuilder
Helper method for creating StringBuilder objects.static <T> LinkedHashSet<T>
set
(T... values) Shortcut for creating a modifiable set out of an array of values.static String
Gets the simple class name of the specified object.Splits a comma-delimited list into a list of strings.Splits a character-delimited string into a string array.Same assplita(String, char)
but limits the number of tokens returned.static void
Same assplita(String,char)
but consumes the tokens instead of creating an array.static void
Same assplita(String)
but consumes the tokens instead of creating an array.static String[]
Splits a comma-delimited list into an array of strings.static String[]
Same assplita(String, char)
except splits all strings in the input and returns a single result.static String[]
Splits a character-delimited string into a string array.static String[]
Same assplita(String, char)
but limits the number of tokens returned.Splits a list of key-value pairs into an ordered map.static String[]
Splits the method arguments in the signature of a method.Splits a comma-delimited list containing "nesting constructs".Splits a nested comma-delimited list.static String[]
Splits a space-delimited string with optionally quoted arguments.static String[]
splitQuoted
(String s, boolean keepQuotes) Same assplitQuoted(String)
but allows you to optionally keep the quote characters.static final List<?>
Converts various collection-like objects to aList
.Converts an array to a stream of objects.static <T> void
Traverses all elements in the specified object and executes a consumer for it.static <T> List<T>
Creates an unmodifiable view of the specified list.static <K,
V> Map<K, V> Creates an unmodifiable view of the specified map.static <T> Set<T>
Creates an unmodifiable view of the specified set.
-
Constructor Details
-
Utils
protected Utils()Constructor - This class is meant to be subclasses.
-
-
Method Details
-
a
Creates an array of objects.- Type Parameters:
T
- The component type of the array.- Parameters:
x
- The objects to place in the array.- Returns:
- A new array containing the specified objects.
-
accumulate
Traverses all elements in the specified object and accumulates them into a list.- Type Parameters:
T
- The element type.- Parameters:
o
- The object to traverse.- Returns:
- A list containing all accumulated elements.
-
alist
Shortcut for creating an unmodifiable list out of an array of values.- Type Parameters:
T
- The element type.- Parameters:
values
- The values to add to the list.- Returns:
- An unmodifiable list containing the specified values, or
null if the input isnull .
-
array
Converts the specified collection to an array.- Type Parameters:
E
- The element type.- Parameters:
value
- The collection to convert.componentType
- The component type of the array.- Returns:
- A new array.
-
arrayToList
Converts any array (including primitive arrays) to a List.- Parameters:
array
- The array to convert. Can be any array type including primitives.- Returns:
- A List containing the array elements. Primitive values are auto-boxed. Returns null if the input is null.
- Throws:
IllegalArgumentException
- if the input is not an array.
-
assertArg
public static final void assertArg(boolean expression, String msg, Object... args) throws IllegalArgumentException Throws anIllegalArgumentException
if the specified expression isfalse .Example:
import static org.apache.juneau.internal.ArgUtils.*;public String setFoo(List<String>foo ) {assertArg (foo !=null && !foo .isEmpty(),"'foo' cannot be null or empty." ); ... }- Parameters:
expression
- The boolean expression to check.msg
- The exception message.args
- The exception message args.- Throws:
IllegalArgumentException
- Constructed exception.
-
assertArgNotNull
Throws anIllegalArgumentException
if the specified argument isnull .Example:
import static org.apache.juneau.internal.ArgUtils.*;public String setFoo(Stringfoo ) {assertArgNotNull ("foo" ,foo ); ... }- Type Parameters:
T
- The argument data type.- Parameters:
name
- The argument name.o
- The object to check.- Returns:
- The same argument.
- Throws:
IllegalArgumentException
- Constructed exception.
-
assertArgNotNullOrBlank
public static final String assertArgNotNullOrBlank(String name, String o) throws IllegalArgumentException Throws anIllegalArgumentException
if the specified string isnull or blank.- Parameters:
name
- The argument name.o
- The object to check.- Returns:
- The same object.
- Throws:
IllegalArgumentException
- Thrown if the specified string isnull or blank.
-
assertVarargsNotNull
public static final <T> T[] assertVarargsNotNull(String name, T[] o) throws IllegalArgumentException Throws anIllegalArgumentException
if the specified varargs array or any of its elements arenull .- Type Parameters:
T
- The element type.- Parameters:
name
- The argument name.o
- The object to check.- Returns:
- The same object.
- Throws:
IllegalArgumentException
- Thrown if the specified varargs array or any of its elements arenull .
-
assertClassArrayArgIsType
public static final <E> Class<E>[] assertClassArrayArgIsType(String name, Class<E> type, Class<?>[] value) throws IllegalArgumentException Throws anIllegalArgumentException
if the specified value doesn't have all subclasses of the specified type.- Type Parameters:
E
- The element type.- Parameters:
name
- The argument name.type
- The expected parent class.value
- The array value being checked.- Returns:
- The value cast to the specified array type.
- Throws:
IllegalArgumentException
- Constructed exception.
-
cast
Casts an object to a specific type if it's an instance of that type.- Type Parameters:
T
- The type to cast to.- Parameters:
c
- The type to cast to.o
- The object to cast to.- Returns:
- The cast object, or
null if the object wasn't the specified type.
-
castOrNull
If the specified object is an instance of the specified class, casts it to that type.- Type Parameters:
T
- The class to cast to.- Parameters:
o
- The object to cast.c
- The class to cast to.- Returns:
- The cast object, or
null if the object wasn't an instance of the specified class.
-
compare
Compares two objects for equality.Nulls are always considered less-than unless both are null.
- Parameters:
o1
- Object 1.o2
- Object 2.- Returns:
-1 ,0 , or1 ifo1 is less-than, equal, or greater-thano2 .0 if objects are not of the same type or do not implement theComparable
interface.
-
contains
Null-safeString.contains(CharSequence)
operation.- Parameters:
s
- The string to check.values
- The characters to check for.- Returns:
true if the string contains any of the specified characters.
-
contains
Null-safeString.contains(CharSequence)
operation.- Parameters:
s
- The string to check.values
- The substrings to check for.- Returns:
true if the string contains any of the specified substrings.
-
ea
Creates an empty array of the specified type.- Type Parameters:
T
- The component type of the array.- Parameters:
type
- The component type class.- Returns:
- An empty array of the specified type.
-
elist
Shortcut for creating an empty list of the specified type.- Type Parameters:
T
- The element type.- Parameters:
type
- The element type class.- Returns:
- An empty list.
-
emap
Shortcut for creating an empty map of the specified types.- Type Parameters:
K
- The key type.V
- The value type.- Parameters:
keyType
- The key type class.valueType
- The value type class.- Returns:
- An empty unmodifiable map.
-
empty
Returns an emptyOptional
.- Type Parameters:
T
- The component type.- Returns:
- An empty
Optional
.
-
emptyIfNull
Returns the specified string, or blank if that string is null.- Parameters:
value
- The value to convert to a string.- Returns:
- The string representation of the value, or an empty string if
null .
-
env
Looks up a system property or environment variable.First looks in system properties. Then converts the name to env-safe and looks in the system environment. Then returns the default if it can't be found.
- Parameters:
name
- The property name.- Returns:
- The value if found.
-
env
Looks up a system property or environment variable.First looks in system properties. Then converts the name to env-safe and looks in the system environment. Then returns the default if it can't be found.
- Type Parameters:
T
- The type to convert the value to.- Parameters:
name
- The property name.def
- The default value if not found.- Returns:
- The default value.
-
eq
Tests two strings for equality, but gracefully handles nulls.- Parameters:
caseInsensitive
- Use case-insensitive matching.s1
- String 1.s2
- String 2.- Returns:
true if the strings are equal.
-
eq
Tests two objects for equality, gracefully handling nulls and arrays.- 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.
-
eq
Tests two objects for equality, gracefully handling nulls. Allows you to simplify object comparison without sacrificing efficiency. Example: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)); }
- Type Parameters:
T
- Object 1 type.U
- Object 2 type.- Parameters:
o1
- Object 1.o2
- Object 2.test
- The test to use for equality.- Returns:
true if both objects are equal based on the test.
-
eqic
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
Same as MessageFormat.format().- Parameters:
pattern
- The message pattern.args
- The arguments to substitute into the pattern.- Returns:
- The formatted string.
-
firstNonNull
Returns the first non-null value in the specified array- 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.
-
fms
Creates a formatted string supplier with message arguments for lazy evaluation.This method returns a
Supplier
that 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.Usage Examples:
// Lazy evaluation - string is only formatted if assertion fails assertTrue(condition, fms("Expected {0} but got {1}" , expected, actual));// Can be used anywhere a Supplier<String> is expected Supplier<String>messageSupplier = fms("Processing item {0} of {1}" , i, total);- Parameters:
pattern
- The message pattern using{0} ,{1} , etc. placeholders.args
- The arguments to substitute into the pattern placeholders.- Returns:
- A
Supplier
that will format the string whenget()
is called. - See Also:
-
getMatchPattern3
Converts a string containing"*" meta characters with a regular expression pattern.- Parameters:
s
- The string to create a pattern from.- Returns:
- A regular expression pattern.
-
getMatchPattern3
Converts a string containing"*" meta characters with a regular expression pattern.- Parameters:
s
- The string to create a pattern from.flags
- Regular expression flags.- Returns:
- A regular expression pattern.
-
hash
Shortcut for callingObjects.hash(Object...)
.- Parameters:
values
- The values to hash.- Returns:
- A hash code value for the given values.
-
illegalArg
Creates anIllegalArgumentException
.- Parameters:
msg
- The exception message.args
- The arguments to substitute into the message.- Returns:
- A new IllegalArgumentException with the formatted message.
-
isArray
Checks if the specified object is an array.- Parameters:
o
- The object to check.- Returns:
true if the object is notnull and is an array.
-
isEmpty
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.
-
isEmpty
Returnstrue if string isnull or empty.- Parameters:
o
- The string to check.- Returns:
true if string isnull or empty.
-
isEmptyOrBlank
Returnstrue if specified string isnull or empty or consists of only blanks.- Parameters:
s
- The string to check.- Returns:
true if specified string isnull or empty or consists of only blanks.
-
isNotEmpty
Returnstrue if the specified object is notnull and not empty. Works on any of the following data types: String, CharSequence, Collection, Map, array. All other types are stringified and then checked as a String.- Parameters:
value
- The value being checked.- Returns:
true if the specified object is notnull and not empty.
-
isNotEmpty
Returnstrue if string is notnull and not empty.- Parameters:
o
- The string to check.- Returns:
true if string is notnull and not empty.
-
isNotMinusOne
Returnstrue if the specified number is notnull and not-1 .- Type Parameters:
T
- The value types.- Parameters:
value
- The value being checked.- Returns:
true if the specified number is notnull and not-1 .
-
isNotNull
Returnstrue if the specified object is notnull .- Type Parameters:
T
- The value type.- Parameters:
value
- The value being checked.- Returns:
true if the specified object is notnull .
-
isTrue
Returnstrue if the specified boolean is notnull and istrue .- Parameters:
value
- The value being checked.- Returns:
true if the specified boolean is notnull and istrue .
-
join
Join the specified tokens into a delimited string.- Parameters:
tokens
- The tokens to join.d
- The delimiter.- Returns:
- The delimited string. If
tokens isnull , returnsnull .
-
join
Join the specified tokens into a delimited string.- Parameters:
tokens
- The tokens to join.d
- The delimiter.- Returns:
- The delimited string. If
tokens isnull , returnsnull .
-
join
Joins the specified tokens into a delimited string and writes the output to the specified string builder.- Parameters:
tokens
- The tokens to join.d
- The delimiter.sb
- The string builder to append the response to.- Returns:
- The same string builder passed in as
sb .
-
join
Join the specified tokens into a delimited string.- Parameters:
tokens
- The tokens to join.d
- The delimiter.- Returns:
- The delimited string. If
tokens isnull , returnsnull .
-
join
Join the specified tokens into a delimited string.- Parameters:
tokens
- The tokens to join.d
- The delimiter.- Returns:
- The delimited string. If
tokens isnull , returnsnull .
-
join
Join the specified tokens into a delimited string.- Parameters:
tokens
- The tokens to join.d
- The delimiter.- Returns:
- The delimited string. If
tokens isnull , returnsnull .
-
join
Joins the specified tokens into a delimited string and writes the output to the specified string builder.- Parameters:
tokens
- The tokens to join.d
- The delimiter.sb
- The string builder to append the response to.- Returns:
- The same string builder passed in as
sb .
-
join
Joins the specified tokens into a delimited string.- Parameters:
tokens
- The tokens to join.d
- The delimiter.- Returns:
- The delimited string. If
tokens isnull , returnsnull .
-
join
Join the specified tokens into a delimited string and writes the output to the specified string builder.- Parameters:
tokens
- The tokens to join.d
- The delimiter.sb
- The string builder to append the response to.- Returns:
- The same string builder passed in as
sb .
-
join
Join the specified tokens into a delimited string.- Parameters:
tokens
- The tokens to join.separator
- The delimiter.- Returns:
- The delimited string. If
tokens isnull , returnsnull .
-
joinnl
Joins tokens with newlines.- Parameters:
tokens
- The tokens to concatenate.- Returns:
- A string with the specified tokens contatenated with newlines.
-
list
Shortcut for creating a modifiable list out of an array of values.- Type Parameters:
T
- The element type.- Parameters:
values
- The values to add to the list.- Returns:
- A modifiable list containing the specified values.
-
listOfSize
Convenience method for creating anArrayList
of the specified size.- Type Parameters:
E
- The element type.- Parameters:
size
- The initial size of the list.- Returns:
- A new modifiable list.
-
map
Shortcut for creating a modifiable map out of an array of key-value pairs.- Type Parameters:
K
- The key type.V
- The value type.- Parameters:
values
- The key-value pairs (alternating keys and values).- Returns:
- A modifiable LinkedHashMap containing the specified key-value pairs.
-
n
Returnsnull for the specified type.- Type Parameters:
T
- The type.- Parameters:
type
- The type class.- Returns:
null .
-
na
Returnsnull for the specified array type.- Type Parameters:
T
- The component type.- Parameters:
type
- The component type class.- Returns:
null .
-
ne
Null-safe not-equals check.- Type Parameters:
T
- The object type.- Parameters:
s1
- Object 1.s2
- Object 2.- Returns:
true if the objects are not equal.
-
ne
Tests two objects for inequality, gracefully handling nulls.- Type Parameters:
T
- Object 1 type.U
- Object 2 type.- Parameters:
o1
- Object 1.o2
- Object 2.test
- The test to use for equality.- Returns:
false if both objects are equal based on the test.
-
neic
Tests two strings for non-equality ignoring case, but gracefully handles nulls.- Parameters:
s1
- String 1.s2
- String 2.- Returns:
true if the strings are not equal ignoring case.
-
nlist
Returns a null list.- Type Parameters:
T
- The element type.- Parameters:
type
- The element type class.- Returns:
null .
-
nmap
Returns a null map.- Type Parameters:
K
- The key type.V
- The value type.- Parameters:
keyType
- The key type class.valueType
- The value type class.- Returns:
null .
-
notContains
Null-safe string not-contains operation.- Parameters:
s
- The string to check.values
- The characters to check for.- Returns:
true if the string does not contain any of the specified characters.
-
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.
-
nullIfEmpty3
Returnsnull if the specified string isnull or empty.- Parameters:
s
- The string to check.- Returns:
null if the specified string isnull or empty, or the same string if not.
-
obfuscate
Returns an obfuscated version of the specified string.- Parameters:
s
- The string to obfuscate.- Returns:
- The obfuscated string with most characters replaced by asterisks.
-
opt
Shortcut for callingOptional.ofNullable(Object)
.- 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 .
-
opte
Returns an empty Optional.- Type Parameters:
T
- The object type.- Returns:
- An empty Optional.
-
printLines
Prints all the specified lines to System.out.- Parameters:
lines
- The lines to print.
-
r
Converts an arbitrary object to a readable string format suitable for debugging and testing.This method provides intelligent formatting for various Java types, recursively processing nested structures to create human-readable representations. It's extensively used throughout the Juneau framework for test assertions and debugging output.
Type-Specific Formatting:
- null: Returns
null - Optional: Recursively formats the contained value (or
null if empty) - Collections: Formats as
"[item1,item2,item3]" with comma-separated elements - Maps: Formats as
"{key1=value1,key2=value2}" with comma-separated entries - Map.Entry: Formats as
"key=value" - Arrays: Converts to list format
"[item1,item2,item3]" - Iterables/Iterators/Enumerations: Converts to list and formats recursively
- GregorianCalendar: Formats as ISO instant timestamp
- Date: Formats as ISO instant string (e.g.,
"2023-12-25T10:30:00Z" ) - InputStream: Converts to hexadecimal representation
- Reader: Reads content and returns as string
- File: Reads file content and returns as string
- byte[]: Converts to hexadecimal representation
- Enum: Returns the enum name via
Enum.name()
- All other types: Uses
Object.toString()
Examples:
// Collections r(List.of("a", "b", "c"))// Returns: "[a,b,c]" r(Set.of(1, 2, 3))// Returns: "[1,2,3]" (order may vary) // Maps r(Map.of("foo", "bar", "baz", 123))// Returns: "{foo=bar,baz=123}" // Arrays r(new int[]{1, 2, 3})// Returns: "[1,2,3]" r(new String[]{"a", "b"})// Returns: "[a,b]" // Nested structures r(List.of(Map.of("x", 1), Set.of("a", "b")))// Returns: "[{x=1},[a,b]]" // Special types r(Optional.of("test"))// Returns: "test" r(Optional.empty())// Returns: null r(new Date(1640995200000L))// Returns: "2022-01-01T00:00:00Z" r(MyEnum.FOO)// Returns: "FOO" Recursive Processing:
The method recursively processes nested structures, so complex objects containing collections, maps, and arrays are fully flattened into readable format. This makes it ideal for test assertions where you need to compare complex object structures.
Error Handling:
IO operations (reading files, streams) are wrapped in safe() calls, converting any exceptions to RuntimeExceptions. Binary data (InputStreams, byte arrays) is converted to hexadecimal representation for readability.
- 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:
- null: Returns
-
runtimeException
Creates aRuntimeException
.- Parameters:
msg
- The exception message.args
- The arguments to substitute into the message.- Returns:
- A new RuntimeException with the formatted message.
-
s
Shortcut for converting an object to a string.- Parameters:
val
- The object to convert.- Returns:
- The string representation of the object, or
null if the object isnull .
-
safe
Runs a snippet of code and encapsulates any throwable inside aRuntimeException
.- Parameters:
snippet
- The snippet of code to run.
-
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.
-
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.
-
set
Shortcut for creating a modifiable set out of an array of values.- Type Parameters:
T
- The element type.- Parameters:
values
- The values to add to the set.- Returns:
- A modifiable LinkedHashSet containing the specified values.
-
split
Splits a comma-delimited list into a list of strings.- Parameters:
s
- The string to split.- Returns:
- A list of split strings, or an empty list if the input is
null .
-
split
Splits a character-delimited string into a string array.Does not split on escaped-delimiters (e.g. "\,"); Resulting tokens are trimmed of whitespace.
NOTE: This behavior is different than the Jakarta equivalent. split("a,b,c",',') -> {"a","b","c"} split("a, b ,c ",',') -> {"a","b","c"} split("a,,c",',') -> {"a","","c"} split(",,",',') -> {"","",""} split("",',') -> {} split(null,',') -> null split("a,b\,c,d", ',', false) -> {"a","b\,c","d"} split("a,b\\,c,d", ',', false) -> {"a","b\","c","d"} split("a,b\,c,d", ',', true) -> {"a","b,c","d"}
- Parameters:
s
- The string to split. Can benull .c
- The character to split on.- Returns:
- The tokens, or
null if the string was null.
-
split
Same assplita(String,char)
but consumes the tokens instead of creating an array.- Parameters:
s
- The string to split.c
- The character to split on.consumer
- The consumer of the tokens.
-
split
Same assplita(String, char)
but limits the number of tokens returned.- Parameters:
s
- The string to split. Can benull .c
- The character to split on.limit
- The maximum number of tokens to return.- Returns:
- The tokens, or
null if the string was null.
-
split
Same assplita(String)
but consumes the tokens instead of creating an array.- Parameters:
s
- The string to split.consumer
- The consumer of the tokens.
-
splita
Splits a comma-delimited list into an array of strings.- Parameters:
s
- The string to split.- Returns:
- An array of split strings.
-
splita
Splits a character-delimited string into a string array.Does not split on escaped-delimiters (e.g. "\,"); Resulting tokens are trimmed of whitespace.
NOTE: This behavior is different than the Jakarta equivalent. split("a,b,c",',') -> {"a","b","c"} split("a, b ,c ",',') -> {"a","b","c"} split("a,,c",',') -> {"a","","c"} split(",,",',') -> {"","",""} split("",',') -> {} split(null,',') -> null split("a,b\,c,d", ',', false) -> {"a","b\,c","d"} split("a,b\\,c,d", ',', false) -> {"a","b\","c","d"} split("a,b\,c,d", ',', true) -> {"a","b,c","d"}
- Parameters:
s
- The string to split. Can benull .c
- The character to split on.- Returns:
- The tokens, or
null if the string was null.
-
splita
Same assplita(String, char)
but limits the number of tokens returned.- Parameters:
s
- The string to split. Can benull .c
- The character to split on.limit
- The maximum number of tokens to return.- Returns:
- The tokens, or
null if the string was null.
-
splita
Same assplita(String, char)
except splits all strings in the input and returns a single result.- Parameters:
s
- The string to split. Can benull .c
- The character to split on.- Returns:
- The tokens, or null if the input array was null
-
splitMap
Splits a list of key-value pairs into an ordered map.Example:
String
in ="foo=1;bar=2" ; Mapmap = StringUtils.splitMap (in,';' ,'=' ,true );- Parameters:
s
- The string to split.trim
- Trim strings after parsing.- Returns:
- The parsed map, or null if the string was null.
-
splitMethodArgs
Splits the method arguments in the signature of a method.- Parameters:
s
- The arguments to split.- Returns:
- The split arguments, or null if the input string is null.
-
splitNested
Splits a comma-delimited list containing "nesting constructs". Nesting constructs are simple embedded "{...}" comma-delimted lists. Example: "a{b,c},d" -> ["a{b,c}","d"] Handles escapes and trims whitespace from tokens.- Parameters:
s
- The input string. The results, ornull if the input wasnull .
An empty string results in an empty array.
-
splitNestedInner
Splits a nested comma-delimited list. Nesting constructs are simple embedded "{...}" comma-delimted lists. Example: "a{b,c{d,e}}" -> ["b","c{d,e}"] Handles escapes and trims whitespace from tokens.- Parameters:
s
- The input string. The results, ornull if the input wasnull .
An empty string results in an empty array.
-
splitQuoted
Splits a space-delimited string with optionally quoted arguments.Examples:
"foo" =>["foo"] " foo " =>["foo"] "foo bar baz" =>["foo","bar","baz"] "foo 'bar baz'" =>["foo","bar baz"] "foo \"bar baz\"" =>["foo","bar baz"] "foo 'bar\'baz'" =>["foo","bar'baz"]
- Parameters:
s
- The input string.- Returns:
- The results, or
null if the input wasnull .
An empty string results in an empty array.
-
splitQuoted
Same assplitQuoted(String)
but allows you to optionally keep the quote characters.- Parameters:
s
- The input string.keepQuotes
- Iftrue , quote characters are kept on the tokens.- Returns:
- The results, or
null if the input wasnull .
An empty string results in an empty array.
-
toList
Converts various collection-like objects to aList
.This utility method enables testing of any collection-like object by converting it to a List that can be passed to methods such as TestUtils.assertList().
Supported Input Types:
- List: Returns the input unchanged
- Iterable: Any collection, set, queue, etc. (converted to List preserving order)
- Iterator: Converts iterator contents to List
- Enumeration: Converts enumeration contents to List
- Stream: Converts stream contents to List (stream is consumed)
- Map: Converts map entries to List of Map.Entry objects
- Array: Converts any array type (including primitive arrays) to List
Usage Examples:
// Test a Set Set<String>mySet = Set.of("a" ,"b" ,"c" ); assertList(toList(mySet ),"a" ,"b" ,"c" );// Test an array String[]myArray = {"x" ,"y" ,"z" }; assertList(toList(myArray ),"x" ,"y" ,"z" );// Test a primitive array int []numbers = {1, 2, 3}; assertList(toList(numbers ),"1" ,"2" ,"3" );// Test a Stream Stream<String>myStream = Stream.of("foo" ,"bar" ); assertList(toList(myStream ),"foo" ,"bar" );// Test a Map (converted to entries) Map<String,Integer>myMap = Map.of("a" , 1,"b" , 2); assertList(toList(myMap ),"a=1" ,"b=2" );// Test any Iterable collection Queue<String>myQueue = new LinkedList<>(List.of("first" ,"second" )); assertList(toList(myQueue ),"first" ,"second" );Integration with Testing:
This method is specifically designed to work with testing frameworks to provide a unified testing approach for all collection-like types. Instead of having separate assertion methods for arrays, sets, and other collections, you can convert them all to Lists and use standard list assertion methods.
- Parameters:
o
- The object to convert to a List. Must not be null and must be a supported collection-like type.- Returns:
- A
List
containing the elements from the input object. - Throws:
IllegalArgumentException
- if the input object cannot be converted to a List.- See Also:
-
isConvertibleToList
-
toStream
Converts an array to a stream of objects.- Parameters:
array
- The array to convert.- Returns:
- A new stream.
-
traverse
Traverses all elements in the specified object and executes a consumer for it.- Type Parameters:
T
- The element type.- Parameters:
o
- The object to traverse.c
- The consumer of the objects.
-
u
Creates an unmodifiable view of the specified list.This is a null-safe wrapper around
Collections.unmodifiableList(List)
.- Type Parameters:
T
- The element type.- Parameters:
value
- The list to make unmodifiable. Can be null.- Returns:
- An unmodifiable view of the list, or null if the input was null.
-
u
Creates an unmodifiable view of the specified map.This is a null-safe wrapper around
Collections.unmodifiableMap(Map)
.- Type Parameters:
K
- The key type.V
- The value type.- Parameters:
value
- The map to make unmodifiable. Can be null.- Returns:
- An unmodifiable view of the map, or null if the input was null.
-
u
Creates an unmodifiable view of the specified set.This is a null-safe wrapper around
Collections.unmodifiableSet(Set)
.- Type Parameters:
T
- The element type.- Parameters:
value
- The set to make unmodifiable. Can be null.- Returns:
- An unmodifiable view of the set, or null if the input was null.
-
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.
-
classNameOf
Gets the fully qualified class name of the specified object.- Parameters:
o
- The object to get the class name for.- Returns:
- The fully qualified class name, or
null if the object isnull .
-
simpleClassNameOf
Gets the simple class name of the specified object.- Parameters:
o
- The object to get the simple class name for.- Returns:
- The simple class name, or
null if the object isnull .
-