Master Spring’s Core Utility Classes: Assertions, Collections, IO, and Reflection
This article provides a comprehensive guide to Spring's built‑in utility classes—including Assert, ObjectUtils, StringUtils, CollectionUtils, FileCopyUtils, ResourceUtils, StreamUtils, ReflectionUtils, and AOP helpers—explaining their purpose, common methods, and usage examples to replace redundant custom code.
Assertions
Assertions are logical checks used to verify situations that should never occur.
The -enableassertions JVM flag (introduced in JDK 1.4) enables the assert keyword.
Spring Boot offers the Assert utility class 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 boolean 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 contain non‑blank characters
void hasText(String text, String message);
// require object to be instance of a given type
void isInstanceOf(Class type, Object obj, String message);
// require subType to be assignable to superType
void isAssignable(Class superType, Class subType, String message);Object, Array, Collection Utilities
ObjectUtils
// get class name of an object, returns "null" if object is null
String nullSafeClassName(Object obj);
// get hash code of an object, returns 0 if null
int nullSafeHashCode(Object obj);
// convert primitive array to string, returns "null" if array is null
String nullSafeToString(boolean[] array);
// get identity hash code as hex string, returns 0 if null
String getIdentityHexString(Object obj);
// get display string for an object, returns empty string if null
String getDisplayString(Object obj); // 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
boolean nullSafeEquals(Object o1, Object o2);
// generic empty check for various types (Optional, array, CharSequence, Collection, Map)
boolean isEmpty(Object obj); // append an element to an array and return a new array
<A, O extends A> A[] addObjectToArray(A[] array, O obj);
// convert a primitive array to an Object[] array
Object[] toObjectArray(Object source);StringUtils
// check if a string is null or empty (whitespace counts as non‑empty)
boolean isEmpty(Object str);
// case‑insensitive endsWith check
boolean endsWithIgnoreCase(String str, String suffix);
// case‑insensitive startsWith check
boolean startsWithIgnoreCase(String str, String prefix);
// check if a string contains whitespace
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);
// count occurrences of a substring
int countOccurrencesOf(String str, String sub); // replace a 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 leading and trailing whitespace
String trimWhitespace(String str);
// remove all whitespace
String trimAllWhitespace(String str);
// delete a specific substring
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);
// decode a URL string
String uriDecode(String source, Charset charset); // clean a path, resolving ".."
String cleanPath(String path);
// extract filename from a path
String getFilename(String path);
// extract file extension
String getFilenameExtension(String path);
// compare two paths, handling ".."
boolean pathEquals(String path1, String path2);
// strip filename extension
String stripFilenameExtension(String path);
// get unqualified name after last '.'
String unqualify(String qualifiedName);
// get unqualified name after a custom separator
String unqualify(String qualifiedName, char separator);CollectionUtils
// check if a collection is empty
boolean isEmpty(Collection<?> collection);
// check if a map is empty
boolean isEmpty(Map<?,?> map);
// check if collection contains an instance
boolean containsInstance(Collection<?> collection, Object element);
// check if iterator contains an element
boolean contains(Iterator<?> iterator, Object element);
// check if collection contains any of the given candidates
boolean containsAny(Collection<?> source, Collection<?> candidates);
// check if all elements are unique
boolean hasUniqueObject(Collection<?> collection); // merge array elements into a collection
<E> void mergeArrayIntoCollection(Object array, Collection<E> collection);
// merge properties into a map
<K,V> void mergePropertiesIntoMap(Properties props, Map<K,V> map);
// get last element of a list
<T> T lastElement(List<T> list);
// get last element of a set
<T> T lastElement(Set<T> set);
// find first matching element between two collections
<E> E findFirstMatch(Collection<?> source, Collection<E> candidates);
// find value of a specific type in a collection
<T> T findValueOfType(Collection<?> collection, Class<T> type);
// find value of any of the given types
Object findValueOfType(Collection<?> collection, Class<?>[] types);
// determine common element type in a collection
Class<?> findCommonElementType(Collection<?> collection);File, Resource, IO Stream Utilities
FileCopyUtils
// 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);
// write 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);
// write byte array to OutputStream
void copy(byte[] in, OutputStream out);
// copy InputStream to OutputStream, returns number of bytes copied
int copy(InputStream in, OutputStream out);
// copy Reader to Writer, returns number of characters copied
int copy(Reader in, Writer out);
// write String to Writer
void copy(String in, Writer out);ResourceUtils
// check if a string is a valid URL
static boolean isUrl(String resourceLocation);
// obtain URL from a location string
static URL getURL(String resourceLocation);
// obtain File from a location string (not works inside JAR)
static File getFile(String resourceLocation);StreamUtils
// copy byte array to OutputStream
void copy(byte[] in, OutputStream out);
// copy InputStream to OutputStream, returns number of bytes copied
int copy(InputStream in, OutputStream out);
// copy String to OutputStream with charset
void copy(String in, Charset charset, OutputStream out);
// copy a range from InputStream to OutputStream
long copyRange(InputStream in, OutputStream out, long start, long end);
// read InputStream into byte array
byte[] copyToByteArray(InputStream in);
// read InputStream into String with charset
String copyToString(InputStream in, Charset charset);
// discard all remaining bytes in InputStream
int drain(InputStream in);Reflection and AOP Utilities
ReflectionUtils
// 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 of a class hierarchy
Method[] getAllDeclaredMethods(Class<?> leafClass);
// obtain accessible constructor
Constructor<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes);
// check if 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 if method declares a specific exception
boolean declaresException(Method method, Class<?> exceptionType);
// invoke method without arguments
Object invokeMethod(Method method, Object target);
// invoke method with arguments
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);
// 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 from source to destination
void shallowCopyFieldState(Object src, Object dest);
// make field accessible
void makeAccessible(Field field);
// apply callback to each field of a class
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
// 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();
// obtain the target class behind a proxy
Class<?> getTargetClass();AopContext
// obtain 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.
