Backend Development 19 min read

Spring Boot Built‑in Utility Classes Overview

This article introduces the most commonly used Spring Boot utility classes—including assertions, object and collection helpers, file/IO utilities, reflection, and AOP support—providing code examples and usage guidelines to help Java backend developers write cleaner, more efficient code.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Spring Boot Built‑in Utility Classes Overview

Spring Boot, as a rapid‑development framework, ships with a rich set of utility classes that greatly improve developer productivity. The following sections summarize the key utilities and demonstrate their usage with code snippets.

Assertions

Logical checks to guard against impossible conditions.

The Assert keyword was introduced in JDK 1.4 and can be enabled with the JVM flag -enableassertions .

Spring Boot provides the Assert utility class for data validation.

// require the argument object to be non‑null, otherwise throw an exception
void notNull(Object object, String message)
// require the argument to be null, otherwise throw an exception
void isNull(Object object, String message)
// require the argument to be true, otherwise throw an exception
void isTrue(boolean expression, String message)
// require a collection to be non‑empty, otherwise throw an exception
void notEmpty(Collection
collection, String message)
// require a string to have length (not empty)
void hasLength(String text, String message)
// require a string to contain non‑blank characters
void hasText(String text, String message)
// require the argument to be an instance of the given type
void isInstanceOf(Class
type, Object obj, String message)
// require subType to be a subclass or implementation of superType
void isAssignable(Class
superType, Class
subType, String message)

Objects, Arrays, Collections

ObjectUtils

1. Retrieve basic object information

// get the class name of an object; returns "null" if the argument is null
String nullSafeClassName(Object obj)
// get the hash code of an object; returns 0 if null
int nullSafeHashCode(Object object)
// convert a boolean array to a string representation; returns "null" if null
String nullSafeToString(boolean[] array)
// get a hexadecimal string of the object's identity hash code; returns "0" if null
String getIdentityHexString(Object obj)
// get a string containing the class name and hash code; returns "" if null
String identityToString(Object obj)
// similar to toString(), but returns "" for null
String getDisplayString(Object obj)

2. Collection‑related checks

// check if an array is empty
boolean isEmpty(Object[] array)
// check if an object is an array
boolean isArray(Object obj)
// check if an array contains a specific element
boolean containsElement(Object[] array, Object element)
// null‑safe equality check (handles nulls)
boolean nullSafeEquals(Object o1, Object o2)
// generic emptiness check for Object (handles Optional, arrays, CharSequence, Collection, Map)
boolean isEmpty(Object obj)

3. Other helper methods

// append a new element to the end of an array and return a new array
A[] addObjectToArray(A[] array, O obj)
// convert a primitive array to an Object[] array
Object[] toObjectArray(Object source)

StringUtils

1. String validation utilities

// check if a string is null or empty (""), whitespace does not count as empty
boolean isEmpty(Object str)
// case‑insensitive check whether a string ends with a suffix
boolean endsWithIgnoreCase(String str, String suffix)
// case‑insensitive check whether a string starts with a prefix
boolean startsWithIgnoreCase(String str, String prefix)
// check if a string contains any whitespace characters
boolean containsWhitespace(String str)
// check if a CharSequence has length > 0
boolean hasLength(CharSequence str)
// check if a CharSequence contains non‑whitespace characters
boolean hasText(CharSequence str)
// check if a substring matches at a given index
boolean substringMatch(CharSequence str, int index, CharSequence substring)
// count occurrences of a substring within a string
int countOccurrencesOf(String str, String sub)

2. String manipulation utilities

// replace all occurrences of a pattern with a new string
String replace(String inString, String oldPattern, String newPattern)
// trim a specific trailing character from a string
String trimTrailingCharacter(String str, char trailingCharacter)
// trim a specific leading character from a string
String trimLeadingCharacter(String str, char leadingCharacter)
// trim leading whitespace
String trimLeadingWhitespace(String str)
// trim trailing whitespace
String trimTrailingWhitespace(String str)
// trim both leading and trailing whitespace
String trimWhitespace(String str)
// remove all whitespace characters from a string
String trimAllWhitespace(String str)
// delete a specific substring
String delete(String inString, String pattern)
// delete any of the given characters from a string
String deleteAny(String inString, String charsToDelete)
// trim whitespace from each element of a string array
String[] trimArrayElements(String[] array)
// decode a URL‑encoded string using the given charset
String uriDecode(String source, Charset charset)

3. Path‑related utilities

// normalize a path, resolving ".." segments
String cleanPath(String path)
// extract the filename from a path
String getFilename(String path)
// extract the file extension from a path
String getFilenameExtension(String path)
// compare two paths for equality, handling ".." automatically
boolean pathEquals(String path1, String path2)
// strip the file‑extension from a path
String stripFilenameExtension(String path)
// return the part after the last occurrence of a separator
String unqualify(String qualifiedName)
String unqualify(String qualifiedName, char separator)

CollectionUtils

1. Collection checks

// check if a collection is empty
boolean isEmpty(Collection
collection)
// check if a map is empty
boolean isEmpty(Map
map)
// check if a collection contains a specific object
boolean containsInstance(Collection
collection, Object element)
// iterate over an iterator to see if it contains an element
boolean contains(Iterator
iterator, Object element)
// check if a collection contains any of the candidates
boolean containsAny(Collection
source, Collection
candidates)
// verify that all elements in a collection are unique
boolean hasUniqueObject(Collection
collection)

2. Collection operations

// merge an array into a collection
void mergeArrayIntoCollection(Object array, Collection
collection)
// merge properties into a map
void mergePropertiesIntoMap(Properties props, Map
map)
// get the last element of a list
T lastElement(List
list)
// get the last element of a set
T lastElement(Set
set)
// find the first element in candidates that exists in source
E findFirstMatch(Collection
source, Collection
candidates)
// find a value of a given type in a collection
T findValueOfType(Collection
collection, Class
type)
// find a value of any of the given types in a collection
Object findValueOfType(Collection
collection, Class
[] types)
// determine the common element type of a collection
Class
findCommonElementType(Collection
collection)

File, Resource, IO Streams

FileCopyUtils

1. Input operations

// read a file into a byte array
byte[] copyToByteArray(File in)
// read an InputStream into a byte array
byte[] copyToByteArray(InputStream in)
// read a Reader into a String
String copyToString(Reader in)

2. Output operations

// write a byte array to a file
void copy(byte[] in, File out)
// copy a file to another file, returning the number of bytes copied
int copy(File in, File out)
// write a byte array to an OutputStream
void copy(byte[] in, OutputStream out)
// copy an InputStream to an OutputStream, returning the number of bytes copied
int copy(InputStream in, OutputStream out)
// copy a Reader to a Writer
int copy(Reader in, Writer out)
// write a String to a Writer
void copy(String in, Writer out)

ResourceUtils

1. Resolve resources from a location string

// check whether a location string is a valid URL
static boolean isUrl(String resourceLocation)
// obtain a URL from a location string
static URL getURL(String resourceLocation)
// obtain a File from a location string (does not work for resources inside JARs)
static File getFile(String resourceLocation)

2. Resource operations

// file‑system resource, e.g., D:\...
FileSystemResource
// URL resource, e.g., file:// or http://
UrlResource
// class‑path resource, e.g., classpath:...
ClassPathResource
// servlet‑context resource (inside a web container)
ServletContextResource
// check if the resource exists
boolean exists()
// obtain a File handle from the resource
File getFile()
// obtain a URI from the resource
URI getURI()
// obtain a URL from the resource
URL getURL()
// obtain an InputStream from the resource
InputStream getInputStream()
// obtain a description of the resource
String getDescription()

StreamUtils

1. Input utilities

// copy a byte array to an OutputStream
void copy(byte[] in, OutputStream out)
// copy an InputStream to an OutputStream, returning the number of bytes copied
int copy(InputStream in, OutputStream out)
// copy a String to an OutputStream using a charset
void copy(String in, Charset charset, OutputStream out)
// copy a range of bytes from an InputStream to an OutputStream
long copyRange(InputStream in, OutputStream out, long start, long end)

2. Output utilities

// read an InputStream into a byte array
byte[] copyToByteArray(InputStream in)
// read an InputStream into a String using a charset
String copyToString(InputStream in, Charset charset)
// discard all remaining bytes in an InputStream
int drain(InputStream in)

Reflection and AOP

ReflectionUtils

1. Method discovery

// find a method by name in a class
Method findMethod(Class
clazz, String name)
// find a method by name and parameter types
Method findMethod(Class
clazz, String name, Class
... paramTypes)
// obtain all declared methods of a class (including inherited)
Method[] getAllDeclaredMethods(Class
leafClass)
// obtain a specific constructor and make it accessible
Constructor
accessibleConstructor(Class
clazz, Class
... parameterTypes)
// check if a method is equals(), hashCode(), toString(), or inherited from Object
boolean isEqualsMethod(Method method)
boolean isHashCodeMethod(Method method)
boolean isToStringMethod(Method method)
boolean isObjectMethod(Method method)
// check whether a method declares a specific exception
boolean declaresException(Method method, Class
exceptionType)

2. Method invocation

// invoke a method without arguments
Object invokeMethod(Method method, Object target)
// invoke a method with arguments
Object invokeMethod(Method method, Object target, Object... args)
// make a method accessible (bypass Java access checks)
void makeAccessible(Method method)
// make a constructor accessible
void makeAccessible(Constructor
ctor)

3. Field handling

// find a field by name
Field findField(Class
clazz, String name)
// find a field by name and type
Field findField(Class
clazz, String name, Class
type)
// check if a field is public static final
boolean isPublicStaticFinal(Field field)
// get the value of a field from a target object
Object getField(Field field, Object target)
// set the value of a field on a target object
void setField(Field field, Object target, Object value)
// shallow copy field state from src to dest
void shallowCopyFieldState(Object src, Object dest)
// make a field accessible
void makeAccessible(Field field)
// apply a callback to each field of a class
void doWithFields(Class
clazz, ReflectionUtils.FieldCallback fc)
// same as above with a field filter
void doWithFields(Class
clazz, ReflectionUtils.FieldCallback fc, ReflectionUtils.FieldFilter ff)
// apply a callback only to fields declared locally (no inheritance)
void doWithLocalFields(Class
clazz, ReflectionUtils.FieldCallback fc)

AopUtils

1. Proxy type checks

// check if an object is a Spring AOP proxy
boolean isAopProxy(Object obj)
// check if an object is a JDK dynamic proxy
boolean isJdkDynamicProxy(Object obj)
// check if an object is a CGLIB proxy
boolean isCglibProxy(Object obj)

2. Retrieve the target class of a proxy

// obtain the underlying target class of a proxy
Class
getTargetClass(Object proxy)

AopContext

1. Access the current proxy

// obtain the current AOP proxy for the invoking object
Object currentProxy()

Understanding and leveraging these Spring Boot utilities enables developers to write more concise, robust, and maintainable backend code, reducing boilerplate and minimizing the chance of errors.

JavaBackend DevelopmentreflectionSpring BootIOAssertionsUtility Classes
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.