Class Utils

java.lang.Object
org.apache.juneau.commons.utils.Utils

public class Utils extends Object
Common utility methods.

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:
  • Constructor Details

    • Utils

      protected Utils()
      Constructor - This class is meant to be subclasses.
  • Method Details

    • bool

      public static boolean bool(Object val)
      Converts an object to a boolean.
      Parameters:
      val - The object to convert.
      Returns:
      The boolean value, or false if the value was null.
    • cast

      public static <T> T cast(Class<T> c, Object o)
      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 a ClassCastException. 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"; String str = cast(String.class, obj); // "Hello" Integer num = cast(Integer.class, obj); // null (not an Integer, no exception thrown) String str2 = 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 was null.
    • cn

      public static String cn(Object value)
      Shortcut for calling ClassUtils.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

      public static String cns(Object value)
      Shortcut for calling ClassUtils.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

      public static String cnsq(Object value)
      Shortcut for calling ClassUtils.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

      public static int cmp(Object o1, Object o2)
      Compares two objects for ordering.

      This method attempts to compare two objects using their natural ordering if they implement Comparable and are of the same type. Null handling:

      • Both null → returns 0 (equal)
      • First null → returns -1 (null is less-than)
      • Second null → returns 1 (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, or 1 if o1 is less-than, equal, or greater-than o2. Returns 0 if objects are not of the same type or do not implement the Comparable interface.
    • lt

      public static <T extends Comparable<T>> boolean lt(T o1, T o2)
      Tests if the first object is less than the second object.

      Uses natural ordering if both objects implement Comparable and 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 if o1 is less than o2.
      See Also:
    • lte

      public static <T extends Comparable<T>> boolean lte(T o1, T o2)
      Tests if the first object is less than or equal to the second object.

      Uses natural ordering if both objects implement Comparable and 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 if o1 is less than or equal to o2.
      See Also:
    • gt

      public static <T extends Comparable<T>> boolean gt(T o1, T o2)
      Tests if the first object is greater than the second object.

      Uses natural ordering if both objects implement Comparable and 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 if o1 is greater than o2.
      See Also:
    • gte

      public static <T extends Comparable<T>> boolean gte(T o1, T o2)
      Tests if the first object is greater than or equal to the second object.

      Uses natural ordering if both objects implement Comparable and 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 if o1 is greater than or equal to o2.
      See Also:
    • ea

      public static <T> T[] ea(Class<T> type)
      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

      public static String emptyIfNull(Object value)
      Returns the string representation of an object, or an empty string if the object is null.

      This is a null-safe string conversion method. If the object is null, returns an empty string. Otherwise, returns the result of calling Object.toString() on the object.

      Example:

      emptyIfNull("Hello"); // "Hello" emptyIfNull(123); // "123" emptyIfNull(null); // ""

      Parameters:
      value - The value to convert to a string. Can be null.
      Returns:
      The string representation of the value, or an empty string if null.
      See Also:
    • env

      public static StringSetting env(String name)
      Looks up a system property or environment variable.

      This method searches for a value in the following order:

      1. System properties (via System.getProperty(String))
      2. Environment variables (via System.getenv(String)) - the name is converted to env-safe format

      Returns an empty Optional if 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 Optional containing the value if found, or empty if not found.
      See Also:
    • env

      public static <T> T env(String name, T def)
      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:

      1. System properties (via System.getProperty(String))
      2. Environment variables (via System.getenv(String)) - the name is converted to env-safe format
      3. 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 Boolean flag = env("my.property", false); // true // Environment variable: MY_PROPERTY=UTF-8 Charset charset = env("my.property", Charset.defaultCharset()); // UTF-8 // Not found, returns default String value = 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:
    • eq

      public static boolean eq(boolean caseInsensitive, String s1, String s2)
      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

      public static <T> boolean eq(T o1, T o2)
      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 the Object.equals(Object) method.
      See Also:
    • eq

      public 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.

      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 Role r1 = new Role(1, "admin"); Role r2 = 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 are null, or if they are the same reference.
      See Also:
    • eqic

      public static boolean eqic(Object o1, Object o2)
      Convenience method for calling StringUtils.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

      public static boolean eqic(String s1, String s2)
      Convenience method for calling StringUtils.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

      public static String f(String pattern, Object... args)
      Shortcut for calling StringUtils.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:
    • firstNonNull

      @SafeVarargs public static <T> T firstNonNull(T... t)
      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 only null values.
      See Also:
    • or

      @SafeVarargs public static <T> T or(T... t)
      Shortcut for calling firstNonNull(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 are null.
      See Also:
    • def

      public static <T> T def(T value, T defaultValue)
      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 if value is null.
      Returns:
      The value if not null, otherwise the default value.
    • and

      @SafeVarargs public static boolean and(boolean... values)
      Returns true if all specified boolean values are true.

      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 are true.
    • or

      @SafeVarargs public static boolean or(boolean... values)
      Returns true if any of the specified boolean values are true.

      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 is true.
    • not

      public static boolean not(boolean value)
      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

      public static <T extends Comparable<T>> T min(T o1, T o2)
      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

      public static <T extends Comparable<T>> T max(T o1, T o2)
      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

      public static <T extends Number> T abs(T value)
      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

      public static Supplier<String> fs(String pattern, Object... args)
      Creates a formatted string supplier with format arguments for lazy evaluation.

      This method returns a Supplier that formats the string pattern with the provided arguments only when the supplier's get() 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. See f(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 Supplier that will format the string when get() is called.
      See Also:
    • h

      public static final int h(Object... values)
      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 as Objects.hash(Object...) (31 * result + element hash).

      Special handling is provided for:

      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:
    • id

      public static String id(Object o)
      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

      public static boolean isArray(Object o)
      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 not null and is an array.
      See Also:
    • isBetween

      public static boolean isBetween(int n, int lower, int higher)
      Returns true 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

      public static boolean e(CharSequence str)
      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

      public static boolean e(Collection<?> o)
      Checks if the specified collection is null or empty.

      This is a null-safe operation. Returns true if the collection is null 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 is null or empty.
      See Also:
    • e

      public static boolean e(Map<?,?> o)
      Checks if the specified map is null or empty.

      This is a null-safe operation. Returns true if the map is null 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 is null or empty.
      See Also:
    • e

      public static boolean e(Object o)
      Returns true 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

      public static boolean ne(CharSequence o)
      Checks if the specified string is not null 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 not null and not empty.
      See Also:
    • ne

      public static boolean ne(Collection<?> value)
      Checks if the specified collection is not null 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 not null and not empty.
      See Also:
    • ne

      public static boolean ne(Map<?,?> value)
      Checks if the specified map is not null 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 not null and not empty.
      See Also:
    • ne

      public static boolean ne(Object value)
      Checks if the specified object is not null 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 not null and not empty.
      See Also:
    • nm1

      public static <T extends Number> boolean nm1(T value)
      Checks if the specified number is not null 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 not null and not -1.
    • n

      public static <T> boolean n(T value)
      Returns true if the specified object is null.

      Equivalent to value == null, but with a more readable method name.

      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 is null.
      See Also:
    • n

      public static boolean n(Object... values)
      Returns true if all specified values are null.

      If the values array itself is null, returns true. If any value in the array is not null, returns false.

      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 are null (or the array is null), false otherwise.
    • isTrue

      public static boolean isTrue(Boolean value)
      Checks if the specified Boolean is not null and is true.

      This is a null-safe way to check if a Boolean wrapper is true. Returns false if the value is null or false.

      Example:

      isTrue(true); // true isTrue(false); // false isTrue(null); // false

      Parameters:
      value - The value being checked.
      Returns:
      true if the specified boolean is not null and is true.
    • lc

      public static String lc(String value)
      Convenience method for calling StringUtils.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 was null.
    • mem

      public static <T> OptionalSupplier<T> mem(Supplier<T> supplier)
      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 ExpensiveObject obj1 = supplier.get(); // Subsequent calls return the cached value (no recomputation) ExpensiveObject obj2 = supplier.get(); // Same instance as obj1

      Thread Safety:

      The implementation uses AtomicReference with 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 returns null.
      • Once cached, the value never changes (immutable after first computation).
      • The returned supplier does not support Object.toString(), Object.equals(Object), or Object.hashCode().
      Type Parameters:
      T - The type of value supplied.
      Parameters:
      supplier - The supplier to memoize. Must not be null.
      Returns:
      A thread-safe memoizing wrapper around the supplier.
      Throws:
      NullPointerException - if supplier is null.
    • memr

      public static <T> ResettableSupplier<T> memr(Supplier<T> supplier)
      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 a ResettableSupplier that supports clearing the cached value, forcing recomputation on the next call.

      Usage:

      ResettableSupplier<String> supplier = Utils.memr(() -> expensiveComputation()); // First call computes and caches String result1 = supplier.get(); // Subsequent calls return cached value String result2 = supplier.get(); // Reset forces recomputation on next get() supplier.reset(); String result3 = supplier.get(); // Recomputes

      Thread Safety:

      The returned supplier is thread-safe for both ResettableSupplier.get() and ResettableSupplier.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 be null.
      Returns:
      A thread-safe resettable memoizing wrapper around the supplier.
      Throws:
      NullPointerException - if supplier is null.
    • no

      public static <T> T no(Class<T> type)
      Returns null 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

      public static <T> boolean neq(T s1, T s2)
      Null-safe not-equals check.

      This is the inverse of eq(Object, Object). Returns true if the objects are not equal, handling null 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

      public 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.

      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"); Role r2 = 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 is null and the other is not.
      See Also:
    • neqic

      public static boolean neqic(String s1, String s2)
      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

      public static boolean nn(Object o)
      Returns true if the specified object is not null.

      Equivalent to o != null, but with a more readable method name.

      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 not null.
    • opt

      public static final <T> Optional<T> opt(T t)
      Shortcut for calling Optional.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

      public static final <T> Optional<T> 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

      public static final void printLines(String[] lines)
      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

      public static String r(Object o)
      Shortcut for calling StringUtils.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 be null.
      Returns:
      A readable string representation of the object, or null if the input was null.
      See Also:
    • s

      public static String s(Object val)
      Shortcut for converting an object to a string.

      This is a null-safe string conversion. Returns null if the object is null, otherwise returns the result of calling Object.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 is null.
      See Also:
    • safe

      public static void safe(Snippet snippet)
      Runs a snippet of code and encapsulates any throwable inside a RuntimeException.
      Parameters:
      snippet - The snippet of code to run.
    • quiet

      public static void quiet(Snippet snippet)
      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 a RuntimeException.

      Parameters:
      snippet - The snippet of code to run.
      See Also:
    • safe

      public static void safe(Snippet snippet, Function<Throwable,RuntimeException> exceptionMapper)
      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

      public static <T> T safe(ThrowingSupplier<T> s)
      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 (InvocationTargetException e) { 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

      public static <T> T safeCatch(ThrowingSupplier<T> s, Function<Throwable,T> exceptionFunction)
      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

      public static <T> Optional<T> safeOpt(ThrowingSupplier<T> s)
      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, returns Optional.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

      public static <T> T safeOrNull(ThrowingSupplier<T> s)
      Executes a supplier that may throw an exception and returns the result or null.

      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 returns null instead of Optional.empty() when an exception occurs. Use this method when you prefer null over Optional for error handling.

      Example:

      // Parse an integer, returning null if parsing fails Integer value = safeOrNull(() -> Integer.valueOf("123")); // 123 Integer invalid = 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

      public 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.
      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

      public static StringBuilder sb(String value)
      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

      public static Supplier<String> ss(Supplier<?> s)
      Parameters:
      s - The supplier.
      Returns:
      A string supplier that calls r(Object) on the supplied value.
    • uc

      public static String uc(String value)
      Convenience method for calling StringUtils.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 was null.
    • b

      public static boolean b(String str)
      Shortcut for calling StringUtils.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

      public static boolean nb(String str)
      Shortcut for calling StringUtils.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

      public static String tr(String str)
      Shortcut for calling StringUtils.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 was null.
      See Also:
    • sw

      public static boolean sw(String str, String prefix)
      Tests if the string starts with the specified prefix.

      Null-safe operation. Returns false if either string is null.

      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

      public static boolean ew(String str, String suffix)
      Tests if the string ends with the specified suffix.

      Null-safe operation. Returns false if either string is null.

      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

      public static boolean co(String str, String substring)
      Tests if the string contains the specified substring.

      Null-safe operation. Returns false if either string is null.

      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

      public static Object unwrap(Object o)
      If the specified object is a Supplier or Value, returns the inner value, otherwise the same value.
      Parameters:
      o - The object to unwrap.
      Returns:
      The unwrapped object.
    • nullIfEmpty

      public static String nullIfEmpty(String value)
      Returns the specified string, or null if that string is null or empty.
      Parameters:
      value - The string value to check.
      Returns:
      The string value, or null if the string is null or empty.
    • nullIfEmpty

      public static <K, V> Map<K,V> nullIfEmpty(Map<K,V> val)
      Returns null if the specified map is null 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 is null or empty, otherwise the map itself.
    • nullIfEmpty

      public static <E> List<E> nullIfEmpty(List<E> val)
      Returns null if the specified list is null 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 is null or empty, otherwise the list itself.
    • nullIfEmpty

      public static <E> Set<E> nullIfEmpty(Set<E> val)
      Returns null if the specified set is null 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 is null or empty, otherwise the set itself.