Spring Framework Utility Classes: Assertions, Object Handling, IO, and Reflection
This article presents a detailed overview of Spring's utility classes, covering assertion helpers, object and collection utilities, file and resource I/O methods, as well as reflection and AOP tools, complete with code examples for each feature.
Spring provides a rich set of utility classes that simplify common programming tasks. This guide collects the most frequently used utilities, explains their purpose, and shows how to apply them in real projects.
1. Assertions
Assertions are logical checks used to verify that impossible conditions do not occur. The Assert class, introduced in JDK 1.4, can be enabled with the JVM flag -enableassertions . Spring Boot offers Assert utilities for data validation.
// Require the parameter object to be non‑null, otherwise throw an exception
void notNull(Object object, String message)
// Require the parameter to be null, otherwise throw an exception
void isNull(Object object, String message)
// Require the parameter to be true, otherwise throw an exception
void isTrue(boolean expression, String message)
// Require a Collection or Set to be non‑empty
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 parameter to be an instance of the given type
void isInstanceOf(Class type, Object obj, String message)
// Require the sub‑type to be assignable to the super‑type
void isAssignable(Class superType, Class subType, String message)2. Objects, Arrays, Collections
The ObjectUtils class offers methods for retrieving basic information about objects.
// Get the class name of an object; returns "null" if the argument is null
String nullSafeClassName(Object obj)
// Return 0 if the object is null, otherwise its hash code
int nullSafeHashCode(Object object)
// Convert a boolean array to a safe string representation; returns "null" for null
String nullSafeToString(boolean[] array)
// Get the identity hash code of an object as a hexadecimal string; returns 0 for null
String getIdentityHexString(Object obj)
// Return a string containing the class name and hash code; returns "" for null
String identityToString(Object obj)
// Similar to toString(), but returns "" when the argument is null
String getDisplayString(Object obj)The StringUtils class provides a comprehensive set of string‑handling utilities.
// Check if a string is null or empty (whitespace counts as non‑empty)
boolean isEmpty(Object str)
// Case‑insensitive check whether a string ends with the given suffix
boolean endsWithIgnoreCase(String str, String suffix)
// Case‑insensitive check whether a string starts with the given prefix
boolean startsWithIgnoreCase(String str, String prefix)
// Determine whether a string contains any whitespace characters
boolean containsWhitespace(String str)
// Check that a CharSequence has length (not empty)
boolean hasLength(CharSequence str)
// Check that a CharSequence has actual text (not just whitespace)
boolean hasText(CharSequence str)
// Check if a substring matches at a specific index
boolean substringMatch(CharSequence str, int index, CharSequence substring)
// Count occurrences of a substring within a string
int countOccurrencesOf(String str, String sub)3. Files, Resources, IO Streams
Spring's FileCopyUtils simplifies copying between files, byte arrays, streams, and strings.
// Copy a file to a byte array
byte[] copyToByteArray(File in)
// Copy an InputStream to a byte array
byte[] copyToByteArray(InputStream in)
// Copy an InputStream to a String
String copyToString(Reader in)
// Copy 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)
// 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 Reader to a Writer
int copy(Reader in, Writer out)
// Copy a String to a Writer
void copy(String in, Writer out)The ResourceUtils class helps resolve resources from various locations.
// Determine whether a string is a valid URL
static boolean isUrl(String resourceLocation)
// Obtain a URL object for the given location
static URL getURL(String resourceLocation)
// Obtain a File object (does not work for resources inside a JAR)
static File getFile(String resourceLocation)The Resource abstraction represents different kinds of resources.
// 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 (for web applications)
ServletContextResource
// Check if the resource exists
boolean exists()
// Get the underlying File object
File getFile()
// Get the resource URI
URI getURI()
// Get the resource URL
URL getURL()
// Obtain an InputStream for reading the resource
InputStream getInputStream()
// Get a description of the resource
String getDescription()The StreamUtils class offers additional stream‑related helpers.
// 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 specific 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)
// Convert an InputStream to a byte array
byte[] copyToByteArray(InputStream in)
// Convert an InputStream to a String using a charset
String copyToString(InputStream in, Charset charset)
// Drain (discard) the contents of an InputStream
int drain(InputStream in)4. Reflection and AOP
Spring's ReflectionUtils simplifies reflective operations.
// 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)
// Get all declared methods of a class, including inherited ones
Method[] getAllDeclaredMethods(Class
leafClass)
// Find 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)
// Determine whether a method declares a particular exception type
boolean declaresException(Method method, Class
exceptionType)Invocation helpers:
// 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, bypassing Java access checks
void makeAccessible(Method method)
// Make a constructor accessible
void makeAccessible(Constructor
ctor)Field utilities:
// 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 or set a field's value on a target object
Object getField(Field field, Object target)
void setField(Field field, Object target, Object value)
// Perform a shallow copy of field values from one object to another
void shallowCopyFieldState(Object src, Object dest)
// Make a field accessible, bypassing Java access checks
void makeAccessible(Field field)
// Iterate over all fields of a class with a callback (optionally filtered)
void doWithFields(Class
clazz, ReflectionUtils.FieldCallback fc)
void doWithFields(Class
clazz, ReflectionUtils.FieldCallback fc, ReflectionUtils.FieldFilter ff)
void doWithLocalFields(Class
clazz, ReflectionUtils.FieldCallback fc)Spring AOP utilities:
// Determine if an object is a Spring AOP proxy
boolean isAopProxy()
// Determine if an object is a JDK dynamic proxy
boolean isJdkDynamicProxy()
// Determine if an object is a CGLIB proxy
boolean isCglibProxy()
// Retrieve the target class behind a proxy
Class
getTargetClass()
// Obtain the current proxy instance from within an advised method
Object currentProxy()These utilities together reduce boiler‑plate code, improve readability, and help developers write safer, more maintainable backend applications.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.