Class Utils
This class contains static utility methods that support various testing scenarios including:
- String formatting and messaging: Methods for formatting messages with parameters
- Object comparison and validation: Equality checking and argument validation
- Pattern matching: Wildcard to regex pattern conversion
- Data conversion: Array to list conversion and Java string escaping
- Exception handling: Safe execution wrappers and assertion utilities
Usage Examples:
Thread Safety: All methods in this class are thread-safe as they are stateless static methods.
-
Method Summary
Modifier and TypeMethodDescriptionConverts an array to aListof objects.static final voidValidates a boolean expression and throws anIllegalArgumentExceptionif false.static final <T> TassertArgNotNull(String name, T o) Validates that an argument is not null and throws anIllegalArgumentExceptionif it is.static org.opentest4j.AssertionFailedErrorassertEqualsFailed(Object expected, Object actual, Supplier<String> messageSupplier) Creates anAssertionFailedErrorfor failed equality assertions.static <T> booleaneq(T o1, T o2) Tests two objects for equality usingObjects.equals(Object, Object).static <T,U> boolean eq(T o1, U o2, BiPredicate<T, U> test) Tests two objects for equality using the provided test predicate.static StringEscapes a string for safe inclusion in Java source code.static StringFormats a message template with parameters usingMessageFormat.Creates aSupplierthat formats a message template with parameters.static PatternConverts a string containing glob-style wildcard characters to a regular expressionPattern.static PatterngetGlobMatchPattern(String s, int flags) Converts a string containing glob-style wildcard characters to a regular expressionPatternwith flags.static <T> booleanne(T o1, T o2) Tests two objects for inequality usingObjects.equals(Object, Object).static <T> Tsafe(ThrowingSupplier<T> s) Safely executes aThrowingSupplierand wraps checked exceptions asRuntimeException.static StringSafely converts an object to its string representation, handling any exceptions that may occur.static StringReturns the simple class name of an object, or null if the object is null.static List<NestedTokenizer.Token>Tokenizes a string into a list ofNestedTokenizer.Tokenobjects.
-
Method Details
-
arrayToList
Converts an array to aListof objects.This method uses reflection to iterate through array elements and convert them to a list. It works with arrays of any type including primitive arrays.
Example:
int []array = {1, 2, 3}; List<Object>list =arrayToList (array );// list contains [1, 2, 3] as Objects - Parameters:
o- The array object to convert. Must be an actual array.- Returns:
- A new
ArrayListcontaining all array elements as objects. - Throws:
IllegalArgumentException- If the object is not an array.NullPointerException- If the array parameter is null.
-
assertArg
public static final void assertArg(boolean expression, String msg, Object... args) throws IllegalArgumentException Validates a boolean expression and throws anIllegalArgumentExceptionif false.This method provides a convenient way to validate method arguments with descriptive error messages. The message template supports
MessageFormatsyntax for parameter substitution.Example:
assertArg (age >= 0,"Age must be non-negative but was {0}" ,age );assertArg (name !=null && !name .isEmpty(),"Name cannot be null or empty" );- Parameters:
expression- The boolean expression to validate.msg- The error message template usingMessageFormatsyntax.args- Optional parameters for the message template.- Throws:
IllegalArgumentException- If the expression evaluates to false.
-
assertArgNotNull
Validates that an argument is not null and throws anIllegalArgumentExceptionif it is.This method provides fluent argument validation by returning the validated argument, allowing it to be used inline in assignment statements.
Example:
public void setUsername(Stringusername ) {this .username =assertArgNotNull ("username" ,username ); }- Type Parameters:
T- The argument data type.- Parameters:
name- The argument name for error reporting.o- The object to validate.- Returns:
- The same argument if not
null . - Throws:
IllegalArgumentException- If the argument is null.
-
assertEqualsFailed
public static org.opentest4j.AssertionFailedError assertEqualsFailed(Object expected, Object actual, Supplier<String> messageSupplier) Creates anAssertionFailedErrorfor failed equality assertions.This method constructs a properly formatted assertion failure with expected and actual values for use in test frameworks. The message follows JUnit's standard format for assertion failures.
Example:
if (ne (expected ,actual )) {throw assertEqualsFailed (expected ,actual , () ->"Custom context message with arg {0}" ,arg ); }- Parameters:
expected- The expected value.actual- The actual value that was encountered.messageSupplier- Optional supplier for additional context message.- Returns:
- A new
AssertionFailedErrorwith formatted message and values.
-
eq
Tests two objects for equality using the provided test predicate.This method provides null-safe equality testing with custom comparison logic. It handles null values appropriately and checks for reference equality before applying the custom test predicate. This method is primarily designed for implementing
equals(Object)methods in a concise and safe manner.Example:
// Implementing equals() method @Override public boolean equals(Object obj) {return (objinstanceof Tokenother ) &&eq (this ,other , (x ,y ) ->eq (x .value ,y .value ) &&eq (x .nested ,y .nested )); }// Case-insensitive string comparison boolean equal =eq (str1 ,str2 , (s1 ,s2 ) ->s1 .equalsIgnoreCase(s2 ));- Type Parameters:
T- The type of the first object.U- The type of the second object.- Parameters:
o1- The first object to compare.o2- The second object to compare.test- The custom equality test predicate.- Returns:
- true if the objects are equal according to the test predicate.
-
eq
public static <T> boolean eq(T o1, T o2) Tests two objects for equality usingObjects.equals(Object, Object).This method provides null-safe equality testing using the standard Java equals contract. It's a convenience wrapper around
<jsm>Objects.equals</jsm>().Example:
boolean equal =eq ("hello" ,"hello" );// true boolean equal =eq (null ,null );// true boolean equal =eq ("hello" ,null );// false - Type Parameters:
T- The type of objects to compare.- Parameters:
o1- The first object to compare.o2- The second object to compare.- Returns:
- true if the objects are equal according to
Objects.equals(Object, Object).
-
escapeForJava
Escapes a string for safe inclusion in Java source code.This method converts special characters to their Java escape sequences and converts non-printable ASCII characters to Unicode escape sequences.
Escape mappings:
"→\"\→\\\n→\\n\r→\\r\t→\\t\f→\\f\b→\\b- Non-printable characters →
\\uXXXX
Example:
var escaped =escapeForJava ("Hello\nWorld\"Test\"" );// Returns: "Hello\\nWorld\\\"Test\\\"" - Parameters:
s- The string to escape.- Returns:
- The escaped string safe for Java source code.
- Throws:
NullPointerException- If the string parameter is null.
-
f
Formats a message template with parameters usingMessageFormat.This method provides convenient message formatting with support for various parameter types. If no arguments are provided, the message is returned as-is. Otherwise, it uses
MessageFormat.format(String, Object...)for parameter substitution.Example:
var msg =f ("User {0} has {1} items" ,"Alice" , 5);// Returns: "User Alice has 5 items" var simple =f ("No parameters" );// Returns: "No parameters" - Parameters:
msg- The message template withMessageFormatplaceholders.args- Optional parameters for template substitution.- Returns:
- The formatted message string.
- Throws:
IllegalArgumentException- If the message format is invalid.
-
fs
Creates aSupplierthat formats a message template with parameters.This method returns a supplier that, when called, will format the message using the
f(String, Object...)method. This is useful for lazy evaluation of expensive formatting operations.Example:
Supplier<String>
msgSupplier =fs ("Processing {0} records" ,recordCount );// Later, when needed: Stringmsg =msgSupplier .get();// "Processing 150 records" - Parameters:
msg- The message template withMessageFormatplaceholders.args- Optional parameters for template substitution.- Returns:
- A
Supplierthat produces the formatted message when called.
-
getGlobMatchPattern
Converts a string containing glob-style wildcard characters to a regular expressionPattern.This method converts glob-style patterns to regular expressions with the following mappings:
*matches any sequence of characters (including none)?matches exactly one character- All other characters are treated literally
Example:
var pattern =getGlobMatchPattern ("user_*_temp" );boolean matches =pattern .matcher("user_alice_temp" ).matches();// true matches =pattern .matcher("user_bob_temp" ).matches();// true matches =pattern .matcher("admin_alice_temp" ).matches();// false - Parameters:
s- The glob-style wildcard pattern string.- Returns:
- A compiled
Patternobject, or null if the input string is null.
-
getGlobMatchPattern
Converts a string containing glob-style wildcard characters to a regular expressionPatternwith flags.This method converts glob-style patterns to regular expressions with the following mappings:
*matches any sequence of characters (including none)?matches exactly one character- All other characters are treated literally
Example:
// Case-insensitive matching var pattern =getGlobMatchPattern ("USER_*" , Pattern.CASE_INSENSITIVE );boolean matches =pattern .matcher("user_alice" ).matches();// true -
ne
public static <T> boolean ne(T o1, T o2) Tests two objects for inequality usingObjects.equals(Object, Object).This method is the logical negation of
eq(Object, Object). It provides null-safe inequality testing using the standard Java equals contract.Example:
boolean notEqual =ne ("hello" ,"world" );// true boolean notEqual =ne ("hello" ,"hello" );// false boolean notEqual =ne (null ,null );// false - Type Parameters:
T- The type of objects to compare.- Parameters:
o1- The first object to compare.o2- The second object to compare.- Returns:
- true if the objects are not equal according to
Objects.equals(Object, Object).
-
safe
Safely executes aThrowingSupplierand wraps checked exceptions asRuntimeException.This method allows checked exceptions to be handled uniformly by converting them to runtime exceptions.
RuntimeExceptions are re-thrown as-is, while checked exceptions are wrapped in a newRuntimeException. Typically used in situations where you want to embed code that throws checked exceptions inside fluent chained method calls.Example:
// Safe file reading without explicit exception handling var content =safe (() -> Files.readString(Paths.get("file.txt" )));// Safe URL connection var response =safe (() -> { URLurl =new URL("http://example.com" );return url .openConnection().getInputStream().readAllBytes(); });- Type Parameters:
T- The return type of the supplier.- Parameters:
s- TheThrowingSupplierto execute safely.- Returns:
- The result of the supplier execution.
- Throws:
RuntimeException- If the supplier throws any checked exception.
-
t
Returns the simple class name of an object, or null if the object is null.This method provides a safe way to get type information for debugging and logging. It handles
null values gracefully by returningnull instead of throwing an exception.Example:
var type =t ("hello" );// "String" type =var t (new ArrayList());// "ArrayList" type =t (null );// null - Parameters:
o- The object to get the type name for.- Returns:
- The simple class name of the object, or
null if the object isnull .
-
tokenize
Tokenizes a string into a list ofNestedTokenizer.Tokenobjects.This method delegates to
NestedTokenizer.tokenize(String)to parse structured field strings into tokens. It's commonly used for parsing field lists and nested property expressions.Example:
var tokens =tokenize ("name,address{street,city},age" );// Parses nested field expressions - Parameters:
fields- The field string to tokenize.- Returns:
- A list of parsed tokens.
- See Also:
-
safeToString
Safely converts an object to its string representation, handling any exceptions that may occur.This method provides a fail-safe way to call
toString()on any object, ensuring that exceptions thrown by problematictoString()implementations don't propagate up the call stack. Instead, it returns a descriptive error message containing the exception type and message.Exception Handling:
If the object's
toString()method throws anyThrowable, this method catches it and returns a formatted string in the form:"<ExceptionType>: <exception message>".Examples:
// Normal case - returns object's toString() result String result =safeToString ("Hello" );// result = "Hello" // Exception case - returns formatted error message Object problematic =new Object() {@Override public String toString() {throw new RuntimeException("Cannot convert" ); } }; String result =safeToString (problematic );// result = "RuntimeException: Cannot convert" Use Cases:
- Object stringification in converters: Safe conversion of arbitrary objects to strings
- Debugging and logging: Ensures log statements never fail due to toString() exceptions
- Error handling: Graceful degradation when objects have problematic string representations
- Third-party object integration: Safe handling of objects from external libraries
- Parameters:
o- The object to convert to a string. May be any object includingnull .- Returns:
- The string representation of the object, or a formatted error message if toString() throws an exception.
Returns
"null" if the object isnull .
-