Comprehensive Guide to Spring Framework Utility Classes and Their Usage
This article presents a detailed overview of Spring's utility classes—including Assert, ObjectUtils, StringUtils, CollectionUtils, FileCopyUtils, ResourceUtils, StreamUtils, ReflectionUtils, and AOP helpers—provides code examples for each, and also contains promotional information about ChatGPT services and a developer community.
Recently the author noticed many duplicated utility classes in a project and realized that Spring already provides most of the needed functionality, so they compiled this guide to help developers.
1. Assertions
Assertions are logical checks to ensure that impossible situations do not occur.
The Assert keyword was introduced in JDK 1.4 and can be enabled with the JVM flag -enableassertions .
Spring Boot offers the Assert utility class for data validation.
// require object to be non‑null, otherwise throw exception
void notNull(Object object, String message)
// require object to be null, otherwise throw exception
void isNull(Object object, String message)
// require expression to be true, otherwise throw exception
void isTrue(boolean expression, String message)
// require collection to be non‑empty
void notEmpty(Collection collection, String message)
// require string to have length (not empty)
void hasLength(String text, String message)
// require string to have text (not blank)
void hasText(String text, String message)
// require object to be instance of type
void isInstanceOf(Class type, Object obj, String message)
// require subType to be a subclass of superType
void isAssignable(Class superType, Class subType, String message)2. Object, Array, Collection Utilities
ObjectUtils provides methods to obtain basic object information.
// get class name, returns "null" if obj is null
String nullSafeClassName(Object obj)
// get hash code, returns 0 if obj is null
int nullSafeHashCode(Object object)
// convert boolean array to string, returns "null" if array is null
String nullSafeToString(boolean[] array)
// get identity hash code as hex string, returns 0 if obj is null
String getIdentityHexString(Object obj)
// get class name and hash code, returns empty string if obj is null
String identityToString(Object obj)
// safe toString, returns empty string if obj is null
String getDisplayString(Object obj)CollectionUtils offers collection‑related checks and operations.
// check if collection is empty
boolean isEmpty(Collection
collection)
// check if map is empty
boolean isEmpty(Map
map)
// check if collection contains an element
boolean containsInstance(Collection
collection, Object element)
// check if iterator contains an element
boolean contains(Iterator
iterator, Object element)
// check if any of the candidates are present in collection
boolean containsAny(Collection
source, Collection
candidates)
// check if collection has unique objects (no duplicates)
boolean hasUniqueObject(Collection
collection)3. String Utilities
StringUtils provides a rich set of string‑handling methods.
// check if string is null or empty (whitespace counts as non‑empty)
boolean isEmpty(Object str)
// check if string ends with suffix, ignoring case
boolean endsWithIgnoreCase(String str, String suffix)
// check if string starts with prefix, ignoring case
boolean startsWithIgnoreCase(String str, String prefix)
// check if string contains whitespace
boolean containsWhitespace(String str)
// check if CharSequence has length (not empty)
boolean hasLength(CharSequence str)
// check if CharSequence has text (not blank)
boolean hasText(CharSequence str)
// check if substring matches at index
boolean substringMatch(CharSequence str, int index, CharSequence substring)
// count occurrences of sub in str
int countOccurrencesOf(String str, String sub)
// replace oldPattern with newPattern
String replace(String inString, String oldPattern, String newPattern)
// trim trailing character
String trimTrailingCharacter(String str, char trailingCharacter)
// trim leading character
String trimLeadingCharacter(String str, char leadingCharacter)
// trim leading whitespace
String trimLeadingWhitespace(String str)
// trim trailing whitespace
String trimTrailingWhitespace(String str)
// trim all whitespace
String trimWhitespace(String str)
// delete all whitespace
String trimAllWhitespace(String str)
// delete pattern from string
String delete(String inString, String pattern)
// delete any of the given characters
String deleteAny(String inString, String charsToDelete)
// trim each element of a string array
String[] trimArrayElements(String[] array)
// URL decode
String uriDecode(String source, Charset charset)4. File, Resource and IO Stream Utilities
FileCopyUtils handles file and stream copying.
// copy file to byte array
byte[] copyToByteArray(File in)
// copy InputStream to byte array
byte[] copyToByteArray(InputStream in)
// copy Reader to String
String copyToString(Reader in)
// copy byte array to File
void copy(byte[] in, File out)
// copy File to File, returns number of bytes copied
int copy(File in, File out)
// copy byte array to OutputStream
void copy(byte[] in, OutputStream out)
// copy InputStream to OutputStream
int copy(InputStream in, OutputStream out)
// copy Reader to Writer
int copy(Reader in, Writer out)
// copy String to Writer
void copy(String in, Writer out)ResourceUtils works with resource locations.
// check if a string is a valid URL
static boolean isUrl(String resourceLocation)
// get URL from location
static URL getURL(String resourceLocation)
// get File from location (cannot be used inside JAR)
static File getFile(String resourceLocation)Resource abstractions for various resource types.
// file system resource
FileSystemResource
// URL resource (e.g., file://, http://)
UrlResource
// class‑path resource
ClassPathResource
// servlet context resource (jar/war)
ServletContextResource
// check existence
boolean exists()
// obtain File, URI, URL, InputStream, description
File getFile()
URI getURI()
URL getURL()
InputStream getInputStream()
String getDescription()StreamUtils provides stream‑related helpers.
// copy byte array to OutputStream
void copy(byte[] in, OutputStream out)
// copy InputStream to OutputStream, returns byte count
int copy(InputStream in, OutputStream out)
// copy String to OutputStream with charset
void copy(String in, Charset charset, OutputStream out)
// copy range of InputStream
long copyRange(InputStream in, OutputStream out, long start, long end)
// read InputStream to byte array
byte[] copyToByteArray(InputStream in)
// read InputStream to String with charset
String copyToString(InputStream in, Charset charset)
// drain InputStream (discard content)
int drain(InputStream in)5. Reflection and AOP Utilities
ReflectionUtils simplifies reflective operations.
// find method by name
Method findMethod(Class
clazz, String name)
// find method by name and parameter types
Method findMethod(Class
clazz, String name, Class
... paramTypes)
// get all declared methods (including inherited)
Method[] getAllDeclaredMethods(Class
leafClass)
// find accessible constructor
Constructor
accessibleConstructor(Class
clazz, Class
... parameterTypes)
// check if method is equals, hashCode, toString, or Object method
boolean isEqualsMethod(Method method)
boolean isHashCodeMethod(Method method)
boolean isToStringMethod(Method method)
boolean isObjectMethod(Method method)
// check if method declares a specific exception
boolean declaresException(Method method, Class
exceptionType)
// invoke method (no args or with args)
Object invokeMethod(Method method, Object target)
Object invokeMethod(Method method, Object target, Object... args)
// make method or constructor accessible (bypass Java access checks)
void makeAccessible(Method method)
void makeAccessible(Constructor
ctor)
// find field by name (optionally by type)
Field findField(Class
clazz, String name)
Field findField(Class
clazz, String name, Class
type)
// check if field is public static final
boolean isPublicStaticFinal(Field field)
// get or set field value
Object getField(Field field, Object target)
void setField(Field field, Object target, Object value)
// shallow copy field state between objects
void shallowCopyFieldState(Object src, Object dest)
// make field accessible
void makeAccessible(Field field)
// iterate over fields with callbacks and optional filters
void doWithFields(Class
clazz, ReflectionUtils.FieldCallback fc)
void doWithFields(Class
clazz, ReflectionUtils.FieldCallback fc, ReflectionUtils.FieldFilter ff)
void doWithLocalFields(Class
clazz, ReflectionUtils.FieldCallback fc)AopUtils helps with Spring AOP proxy handling.
// check if object is a Spring AOP proxy
boolean isAopProxy()
// check if object is a JDK dynamic proxy
boolean isJdkDynamicProxy()
// check if object is a CGLIB proxy
boolean isCglibProxy()
// get target class of a proxy
Class
getTargetClass()AopContext provides access to the current proxy.
Object currentProxy()In addition to the technical content, the article contains promotional messages encouraging readers to join a ChatGPT‑focused community, purchase access to ChatGPT accounts, and follow various links for additional resources and interview material.
Readers are invited to discuss the material, ask questions, and engage with the author through the provided contact information.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.