Utils Package
The org.apache.juneau.commons.utils package provides general-purpose utility classes for common operations including string manipulation, collection operations, class utilities, file operations, and more. It contains the most frequently used utility classes in the codebase — most notably Shorts (a terse one-import alias facade) and StringUtils, which are imported statically across the Juneau ecosystem.
Juneau deliberately favors short, memorable static method names (for example a(...), l(...), m(...), eq(...), nn(...), f(...)) over long descriptive ones. Beyond keeping call sites terse and readable, this conciseness has a practical benefit for AI-assisted development: shorter identifiers cost fewer tokens for a model to generate, so terse APIs are cheaper and faster to produce equivalent code with. They're also easier for LLMs to recall correctly, since a small, consistent vocabulary of names is simpler to memorize than a large set of verbose ones. The static-import style shown throughout this page keeps that vocabulary front-and-center.
Key Classes
Shorts
A terse alias facade. A single wildcard static import exposes short one/two-letter aliases for the most-used helpers; each alias is a one-line delegation to a canonical, fully-descriptive method on a domain class (ObjectUtils, StringUtils, CollectionUtils, ClassUtils, ThrowableUtils, …). This class replaces the former Utils grab-bag (now deleted).
import static org.apache.juneau.commons.utils.Shorts.*;
// Object equality with null handling
eq("Hello", "Hello"); // true
eq(null, null); // true
eq("Hello", null); // false
// Null-safe operations
nn(obj); // Returns true if obj is not null
n(obj); // Returns true if obj is null
// Empty/not-empty checks
ie(""); // true (empty string)
ie(null); // true (null is empty)
ie("Hello"); // false
ine("Hello"); // true (not empty)
ine(""); // false
// Hash code generation
int hash = h("Hello", 123, true);
// Object identity
String id = id(obj); // Returns "ClassName@hashcode"
// Optional utilities
Optional<String> opt = o("value");
Optional<String> empty = oe();
More commonly-used helpers:
import static org.apache.juneau.commons.utils.Shorts.*;
// First non-null value / defaulting
String name = or(nickname, username, "anonymous");
String port = or(configuredPort, "8080"); // 2-arg form of the same varargs coalesce
// Formatting shorthand (printf-style placeholders — String.format semantics)
String msg = f("User %s has %s items", "Alice", 10);
// For MessageFormat-style {0} placeholders (e.g. i18n / .properties patterns), use mf():
String msg2 = mf("User {0} has {1} items", "Alice", 10);
// Comparisons
cmp("apple", "banana"); // < 0
lt(1, 2); // true
gte(5, 5); // true
btw(5, 1, 10); // true (isBetween)
// Case conversion (null-safe)
uc("hello"); // "HELLO"
lc("HELLO"); // "hello"
// Readable string / class name rendering
String s = s(obj); // Null-safe toString()
String r = r(obj); // Readable/debug representation
String cn = cn(obj); // Fully-qualified class name
String sn = cns(obj); // Simple class name
// Run code that throws checked exceptions without try/catch boilerplate
// (safe/safeOpt are canonical ThrowableUtils methods, not Shorts aliases — see below)
String contents = ThrowableUtils.safe(() -> Files.readString(path));
Optional<String> maybe = ThrowableUtils.safeOpt(() -> Files.readString(path));
// Collapse empty values to null
String x = nie(""); // null
min/max/abs (ObjectUtils) and isArray (ClassUtils) have no Shorts alias — call the domain method directly. Supplier memoization moved to org.apache.juneau.commons.function.Suppliers (Suppliers.memoize(...) / Suppliers.memoizer(...), no Shorts alias). The safe* family (safe, safeCatch, safeOpt, safeOptCatch, safeOrNull, safeSupplier) are likewise not Shorts aliases — they're canonical ThrowableUtils methods.
StringUtils
Reusable string utility methods for formatting, parsing, and manipulation.
import static org.apache.juneau.commons.utils.StringUtils.*;
// Format strings (printf-style — String.format semantics)
format("Hello %s, you have %d items", "John", 5);
// For MessageFormat-style {0} placeholders, use mformat():
mformat("Hello {0}, you have {1} items", "John", 5);
// Case-insensitive comparison
equalsIgnoreCase("Hello", "hello"); // true
// String splitting and joining
split("a,b,c", ','); // Returns ["a", "b", "c"]
join(List.of("a", "b", "c"), ","); // Returns "a,b,c"
// Trimming and padding
trim(" hello "); // Returns "hello"
padLeft("42", 5, '0'); // Returns "00042"
padRight("42", 5, '0'); // Returns "42000"
padCenter("42", 6, '.'); // Returns "..42.."
More string helpers:
import static org.apache.juneau.commons.utils.StringUtils.*;
// Empty/blank checks
isEmpty(""); // true
isNotEmpty("x"); // true
isBlank(" "); // true (whitespace-only)
isNotBlank(" x "); // true
// Defaulting
firstNonEmpty(null, "", "found"); // "found"
defaultIfEmpty("", "fallback"); // "fallback"
defaultIfBlank(" ", "fallback"); // "fallback"
// Splitting (char delimiter) and joining
List<String> parts = split("a,b,c", ','); // ["a", "b", "c"]
String[] partsArr = splita("a,b,c", ','); // {"a", "b", "c"}
String joined = join(List.of("a", "b", "c"), ","); // "a,b,c"
// Substrings
substringBefore("user@example.com", "@"); // "user"
substringAfter("user@example.com", "@"); // "example.com"
substringBetween("[value]", "[", "]"); // "value"
left("hello", 3); // "hel"
right("hello", 3); // "llo"
// Transformations
capitalize("hello"); // "Hello"
camelCase("hello-world"); // "helloWorld"
abbreviate("Hello World", 8); // "Hello..."
repeat(3, "ab"); // "ababab"
reverse("abc"); // "cba"
// Searching / counting
contains("hello world", "world"); // true
countMatches("a.b.c.d", "."); // 3
// Validation
isNumeric("12345"); // true
isEmail("user@example.com"); // true
isUri("https://juneau.apache.org"); // true
// IDs and randomness
String uuid = generateUUID();
String token = randomAlphanumeric(16);
// Encoding
String b64 = base64EncodeToString("Hello"); // "SGVsbG8="
String back = base64DecodeToString(b64); // "Hello"
String hex = toHex("AB".getBytes()); // "4142"
CollectionUtils
Utility methods for working with collections, arrays, and maps.
import static org.apache.juneau.commons.utils.CollectionUtils.*;
// Create collections
List<String> list = listBuilder(String.class)
.add("a", "b", "c")
.build();
Map<String, Integer> map = mapBuilder(String.class, Integer.class)
.add("one", 1)
.add("two", 2)
.build();
Set<String> set = setBuilder(String.class)
.add("a", "b", "c")
.build();
// Array utilities
String[] arr = array("a", "b", "c");
List<Object> listFromArray = arrayToList(arr);
Concise literal factories and accessors (the terse Shorts aliases for these are noted inline):
import static org.apache.juneau.commons.utils.CollectionUtils.*;
// Canonical literal factories — list()/map()/set() are all MODIFIABLE by default
String[] arr = array("a", "b", "c"); // array (Shorts alias: a)
List<String> list = list("a", "b", "c"); // modifiable ArrayList (Shorts alias: l)
Map<String,Integer> map = map("one", 1, "two", 2, "three", 3); // modifiable LinkedHashMap, up to 10 pairs (Shorts alias: m)
Set<String> set = set("a", "b", "c"); // modifiable, insertion-ordered LinkedHashSet (Shorts alias: st)
SortedSet<String> sorted = sortedSet("a", "b", "c"); // TreeSet, nulls filtered (Shorts alias: ss)
// Fixed-size / immutable variants have no short alias — call these explicitly
List<String> fixed = fixedSizeList("a", "b", "c"); // Arrays.asList-backed, null-tolerant
Map<String,Integer> immutable = immutableMap("one", 1, "two", 2); // Map.of-style, duplicate-key detection
// Builders (Shorts aliases: lb/mb/stb)
List<String> built = listBuilder(String.class).add("a", "b").build();
// Case-insensitive sorted set
SortedSet<String> ci = treeSetCi(List.of("Banana", "apple", "Cherry"));
// Safe element access (returns Optional)
Optional<String> firstEl = first(list);
String lastEl = last(list);
String second = elementAt(list, 1); // Shorts alias: at
// Reversing
List<String> reversed = reverse(list);
// Appending
List<String> more = addAll(new ArrayList<>(list), "d", "e");
ClassUtils
Utility methods for working with classes, including class-name rendering, type resolution, and reflection access.
import static org.apache.juneau.commons.utils.ClassUtils.*;
// Readable class names for an object (null-safe)
String fqn = className(myBean); // e.g. "com.example.MyBean"
String simpleName = classNameSimple(myBean); // e.g. "MyBean"
// Resolve a java.lang.reflect.Type to its raw Class
Class<?> raw = toClass(myType);
// Make a reflective member accessible (returns true on success)
boolean ok = setAccessible(myMethod);
FileUtils
Utility methods for file operations.
import static org.apache.juneau.commons.utils.FileUtils.*;
// Create a temp file (optionally seeded with contents)
File tmp = createTempFile("data.txt", "content");
// Check whether a file exists within a directory
boolean exists = fileExists(dir, "data.txt");
// Parse file-name components
String ext = getFileExtension("file.txt"); // Returns "txt"
String base = getBaseName("file.txt"); // Returns "file"
String name = getFileName("/path/to/file.txt"); // Returns "file.txt"
IoUtils
Utility methods for I/O operations.
import static org.apache.juneau.commons.utils.IoUtils.*;
// Read an input stream (or Reader/File/Path) as a string
String content = read(inputStream);
// Pipe (copy) bytes from an input stream to an output stream; returns bytes transferred
long transferred = pipe(inputStream, outputStream);
// Pipe characters from a reader to a writer
pipe(reader, writer);
DateUtils
Utility methods for date and time operations.
import static org.apache.juneau.commons.utils.DateUtils.*;
// Get a cached DateTimeFormatter for a pattern, then use the standard java.time API
DateTimeFormatter fmt = getDateTimeFormatter("yyyy-MM-dd");
String formatted = LocalDate.now().format(fmt);
LocalDate parsed = LocalDate.parse("2023-12-25", fmt);
AnnotationUtils
Utility methods for working with annotations.
import static org.apache.juneau.commons.utils.AnnotationUtils.*;
// Value-based equality and hashing for annotation instances
boolean same = equals(annotation1, annotation2);
int hashCode = hash(annotation1);
// Expand a container/repeatable annotation into its repeated members
Stream<Annotation> repeated = streamRepeated(containerAnnotation);
AssertionUtils
Membership assertion utility. The argument and state checks that used to live here moved to Shorts in 10.0 (see the example below); only assertOneOf stays in AssertionUtils.
import static org.apache.juneau.commons.utils.Shorts.*;
// Argument checks (throw IllegalArgumentException)
String value = reqnn("value", obj); // non-null; returns the value
String str = reqnb("str", input); // non-null and non-blank; returns the value
req(count > 0, "count must be positive, was %s", count); // arbitrary condition (printf-style)
// State checks (throw IllegalStateException)
chk(isOpen, "Not open");
Connection c = chknn(connection, "Not connected: %s", name);
PredicateUtils
Utility methods for working with predicates and functional pipelines.
import static org.apache.juneau.commons.utils.PredicateUtils.*;
// Null-safe predicate evaluation (returns false if the predicate is null)
boolean matched = test(myPredicate, value);
// Conditionally consume a value
consumeIf(v -> v > 0, v -> System.out.println(v), value);
// Filter a stream to distinct elements by a derived key
List<Person> unique = people.stream()
.filter(distinctByKey(Person::getEmail))
.collect(toList());
ThrowableUtils
Utilities for inspecting, wrapping, and safely invoking code that may throw.
import static org.apache.juneau.commons.utils.ThrowableUtils.*;
// Wrap any throwable as a RuntimeException
RuntimeException e = toRex(cause);
// Search the cause chain
Optional<IOException> ioEx = findCause(e, IOException.class);
IOException cause2 = getThrowableCause(IOException.class, e);
// Get stack trace as a string / print with a depth limit (safe for StackOverflowError)
String trace = getStackTrace(throwable);
printStackTrace(e, 100);
// Run code that throws checked exceptions without try/catch boilerplate
String contents = safe(() -> Files.readString(path)); // rethrows as RuntimeException
Optional<String> maybe = safeOpt(() -> Files.readString(path)); // empty Optional on failure
String orNull = safeOrNull(() -> Files.readString(path)); // null on failure
Exception factories (creating a new exception, as opposed to inspecting one) live directly on
Shorts as terse, self-contained
methods — they do not delegate to ThrowableUtils:
import static org.apache.juneau.commons.utils.Shorts.*;
throw iaex("Value '%s' is not valid", value); // IllegalArgumentException
throw isex("Component must be initialized before %s", m); // IllegalStateException
throw rex("Unexpected error processing %s", input); // RuntimeException
throw uoex("Method not supported for type %s", type); // UnsupportedOperationException
throw brex(MyBean.class, "Failed to create instance"); // BeanRuntimeException
throw exex(cause, "Error invoking method %s", method); // ExecutableException
throw ioex("Failed to read file %s", path); // IOException
juneau.enableVerboseExceptions Setting
ThrowableUtils.log(exception) is an opt-in helper — it is never invoked automatically by any exception factory. When the juneau.enableVerboseExceptions setting is true, calling it logs the throwable's stack trace as a warning and returns the same throwable unchanged (so it can be used inline, e.g. throw log(iaex("..."))); when the setting is false (the default), it's a no-op passthrough:
# In system properties or Juneau config file
juneau.enableVerboseExceptions = true
// Or programmatically via Settings
Settings.get().setGlobal("juneau.enableVerboseExceptions", "true");
// Wrap a factory call with log(...) at sites where verbose logging is desired
import static org.apache.juneau.commons.utils.Shorts.*;
import static org.apache.juneau.commons.utils.ThrowableUtils.log;
throw log(iaex("Value '%s' is not valid", value));
This is particularly useful when debugging swallowed exceptions or unexpected code paths where you need to identify exactly where an exception was created.
To enable this only for a single test thread without affecting other threads, use a per-thread override:
Settings.get().setLocal("juneau.enableVerboseExceptions", "true");
try {
// ... code under test ...
} finally {
Settings.get().clearLocal();
}
Common Patterns
Fluent Collection Building
import static org.apache.juneau.commons.utils.CollectionUtils.*;
List<String> list = listBuilder(String.class)
.add("a", "b", "c")
.addIf(condition, "d")
.sorted()
.unmodifiable()
.build();
String Formatting
import static org.apache.juneau.commons.utils.StringUtils.*;
// printf-style formatting (String.format semantics)
String result = format("User %s has %d items", "Alice", 10);
// Returns: "User Alice has 10 items"
// For MessageFormat-style {0} placeholders (i18n / .properties), use mformat():
String result2 = mformat("User {0} has {1} items", "Alice", 10);
// Returns: "User Alice has 10 items"
Null-Safe Operations
import static org.apache.juneau.commons.utils.Shorts.*;
// Safe equality check
if (eq(obj1, obj2)) {
// Objects are equal (handles nulls)
}
// Safe null checks
if (nn(obj)) {
// Object is not null
}
if (n(obj)) {
// Object is null
}
// Empty checks
if (ie(collection)) {
// Collection is null or empty
}
if (ine(collection)) {
// Collection is not null and not empty
}