Master Spring’s Built‑In Utility Classes: Assertions, Collections, IO, and Reflection
This article consolidates essential Spring utility classes—including Assert, ObjectUtils, StringUtils, CollectionUtils, FileCopyUtils, ResourceUtils, StreamUtils, ReflectionUtils, and AOP helpers—explaining their purpose, common methods, and usage examples to help developers avoid redundant custom code and leverage built‑in functionality.
I recently noticed colleagues writing many duplicate utility classes, and many of those functions are already provided by Spring. So I organized this article hoping it can help everyone!
Assertions
Assertions are logical checks used to verify situations that should not occur.
The Assert keyword was introduced in JDK 1.4 and can be enabled via the JVM parameter -enableassertions.
Spring Boot provides the Assert utility class, typically used for data validation.
// require parameter object to be non‑null, otherwise throw exception
void notNull(Object object, String message)
// require parameter to be null, otherwise throw exception
void isNull(Object object, String message)
// require parameter 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 parameter to be instance of given 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)Objects, Arrays, Collections
ObjectUtils
Utility methods for obtaining basic information about objects.
// get class name of object; returns "null" if obj is null
String nullSafeClassName(Object obj)
// get hash code of object; returns 0 if null
int nullSafeHashCode(Object object)
// convert boolean array to string; returns "null" if null
String nullSafeToString(boolean[] array)
// get identity hash code as hex string; returns 0 if null
String getIdentityHexString(Object obj)
// get class name and hash code string; returns "" if null
String identityToString(Object obj)
// similar to toString(), returns "" if null
String getDisplayString(Object obj)Additional object utilities:
// check if array is empty
boolean isEmpty(Object[] array)
// check if object is an array
boolean isArray(Object obj)
// check if array contains element
boolean containsElement(Object[] array, Object element)
// null‑safe equality check
boolean nullSafeEquals(Object o1, Object o2)
/* Determine emptiness of various types:
Optional.empty(), array length 0, CharSequence length 0,
Collection.isEmpty(), Map.isEmpty()
*/
boolean isEmpty(Object obj)Other helper methods:
// add element to end of array, returning new array
<A, O extends A> A[] addObjectToArray(A[] array, O obj)
// convert primitive array to wrapper array
Object[] toObjectArray(Object source)StringUtils
String validation utilities.
// 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 string has length (not empty)
boolean hasLength(CharSequence str)
// check if string has text (not blank)
boolean hasText(CharSequence str)
// check substring match at index
boolean substringMatch(CharSequence str, int index, CharSequence substring)
// count occurrences of substring
int countOccurrencesOf(String str, String sub)String manipulation utilities.
// replace substring
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 both ends whitespace
String trimWhitespace(String str)
// trim all whitespace
String trimAllWhitespace(String str)
// delete substring
String delete(String inString, String pattern)
// delete any of specified characters
String deleteAny(String inString, String charsToDelete)
// trim each element in array
String[] trimArrayElements(String[] array)
// decode URL string
String uriDecode(String source, Charset charset)Path‑related utilities.
// clean path, resolving ".."
String cleanPath(String path)
// extract filename from path
String getFilename(String path)
// extract file extension
String getFilenameExtension(String path)
// compare two paths, handling ".."
boolean pathEquals(String path1, String path2)
// strip file extension
String stripFilenameExtension(String path)
// get last segment after '.' delimiter
String unqualify(String qualifiedName)
// get last segment after custom separator
String unqualify(String qualifiedName, char separator)CollectionUtils
Collection validation utilities.
// check if collection is empty
boolean isEmpty(Collection<?> collection)
// check if map is empty
boolean isEmpty(Map<?,?> map)
// check if collection contains element
boolean containsInstance(Collection<?> collection, Object element)
// check if iterator contains element
boolean contains(Iterator<?> iterator, Object element)
// check if collection contains any of candidates
boolean containsAny(Collection<?> source, Collection<?> candidates)
// check if collection elements are unique
boolean hasUniqueObject(Collection<?> collection)Collection manipulation utilities.
// merge array elements into collection
<E> void mergeArrayIntoCollection(Object array, Collection<E> collection)
// merge properties into map
<K,V> void mergePropertiesIntoMap(Properties props, Map<K,V> map)
// get last element of list
<T> T lastElement(List<T> list)
// get last element of set
<T> T lastElement(Set<T> set)
// find first matching element between source and candidates
<E> E findFirstMatch(Collection<?> source, Collection<E> candidates)
// find value of given type in collection
<T> T findValueOfType(Collection<?> collection, Class<T> type)
// find value of any of given types
Object findValueOfType(Collection<?> collection, Class<?>[] types)
// determine common element type in collection
Class<?> findCommonElementType(Collection<?> collection)Files, Resources, IO Streams
FileCopyUtils
Input methods.
// read file into byte array
byte[] copyToByteArray(File in)
// read InputStream into byte array
byte[] copyToByteArray(InputStream in)
// read Reader into String
String copyToString(Reader in)Output methods.
// write byte array to file
void copy(byte[] in, File out)
// copy file to file
int copy(File in, File out)
// write 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)
// write String to Writer
void copy(String in, Writer out)ResourceUtils
Resource path utilities.
// check if string is a valid URL
static boolean isUrl(String resourceLocation)
// get URL from location
static URL getURL(String resourceLocation)
// get File from location (not works inside JAR)
static File getFile(String resourceLocation)Resource interface methods.
// file system resource example: FileSystemResource
// URL resource example: UrlResource
// classpath resource example: ClassPathResource
// servlet context resource example: ServletContextResource
// check if resource exists
boolean exists()
// get File from resource
File getFile()
// get URI from resource
URI getURI()
// get URL from resource
URL getURL()
// get InputStream from resource
InputStream getInputStream()
// get description of resource
String getDescription()StreamUtils
Input utilities.
// copy byte array to OutputStream
void copy(byte[] in, OutputStream out)
// copy InputStream to OutputStream, returning byte count
int copy(InputStream in, OutputStream out)
// copy String to OutputStream with charset
void copy(String in, Charset charset, OutputStream out)
// copy range from InputStream to OutputStream
long copyRange(InputStream in, OutputStream out, long start, long end)Output utilities.
// read InputStream into byte array
byte[] copyToByteArray(InputStream in)
// read InputStream into String with charset
String copyToString(InputStream in, Charset charset)
// discard remaining bytes in InputStream
int drain(InputStream in)Reflection and AOP
ReflectionUtils
Method discovery.
// 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<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes)
// check if method is equals()
boolean isEqualsMethod(Method method)
// check if method is hashCode()
boolean isHashCodeMethod(Method method)
// check if method is toString()
boolean isToStringMethod(Method method)
// check if method is declared on Object
boolean isObjectMethod(Method method)
// check if method declares a specific exception
boolean declaresException(Method method, Class<?> exceptionType)Method invocation.
// invoke method without args
Object invokeMethod(Method method, Object target)
// invoke method with args
Object invokeMethod(Method method, Object target, Object... args)
// make method accessible (bypass Java access checks)
void makeAccessible(Method method)
// make constructor accessible
void makeAccessible(Constructor<?> ctor)Field handling.
// find field by name
Field findField(Class<?> clazz, String name)
// find field by name and type
Field findField(Class<?> clazz, String name, Class<?> type)
// check if field is public static final
boolean isPublicStaticFinal(Field field)
// get field value from target object
Object getField(Field field, Object target)
// set field value on target object
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)
// apply callback to each field
void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc)
// apply callback with field filter
void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc, ReflectionUtils.FieldFilter ff)
// apply callback to local fields only
void doWithLocalFields(Class<?> clazz, ReflectionUtils.FieldCallback fc)AopUtils
Proxy type checks.
// 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()Retrieve target class.
// get the target class behind a proxy
Class<?> getTargetClass()AopContext
Obtain current proxy.
// get the current proxy object
Object currentProxy()Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
