Master Spring’s Assert and Utility Classes: Essential Tips & Code Samples
This guide explains Spring’s Assert utilities and a comprehensive set of core helper classes—including ObjectUtils, StringUtils, CollectionUtils, FileCopyUtils, ResourceUtils, StreamUtils, ReflectionUtils, AopUtils, and AopContext—detailing their purpose, typical use cases, and providing concise code examples for each method.
Assertions
Assertions are logical checks used to verify conditions that should never occur.
The
assertkeyword was introduced in JDK 1.4 and can be enabled with the JVM option
-enableassertions.
Spring Boot provides the
Assertutility class for data validation.
<code>void notNull(Object object, String message);
void isNull(Object object, String message);
void isTrue(boolean expression, String message);
void notEmpty(Collection collection, String message);
void hasLength(String text, String message);
void hasText(String text, String message);
void isInstanceOf(Class type, Object obj, String message);
void isAssignable(Class superType, Class subType, String message);
</code>Object, Array, Collection Utilities
ObjectUtils
Basic object information methods such as class name, hash code, and safe string conversion.
Utility methods for checking emptiness, array type, element containment, and null‑safe equality.
Additional helpers for adding elements to arrays and converting primitive arrays to object arrays.
<code>String nullSafeClassName(Object obj);
int nullSafeHashCode(Object object);
String nullSafeToString(boolean[] array);
String getIdentityHexString(Object obj);
String identityToString(Object obj);
String getDisplayString(Object obj);
boolean isEmpty(Object[] array);
boolean isArray(Object obj);
boolean containsElement(Object[] array, Object element);
boolean nullSafeEquals(Object o1, Object o2);
boolean isEmpty(Object obj);
<A, O extends A> A[] addObjectToArray(A[] array, O obj);
Object[] toObjectArray(Object source);
</code>StringUtils
String validation methods such as emptiness, prefix/suffix checks, whitespace detection, length, and content.
String manipulation methods for replace, trimming, deleting characters, array trimming, and URL decoding.
<code>boolean isEmpty(Object str);
boolean endsWithIgnoreCase(String str, String suffix);
boolean startsWithIgnoreCase(String str, String prefix);
boolean containsWhitespace(String str);
boolean hasLength(CharSequence str);
boolean hasText(CharSequence str);
bool substringMatch(CharSequence str, int index, CharSequence substring);
int countOccurrencesOf(String str, String sub);
String replace(String inString, String oldPattern, String newPattern);
String trimTrailingCharacter(String str, char trailingCharacter);
String trimLeadingCharacter(String str, char leadingCharacter);
String trimLeadingWhitespace(String str);
String trimTrailingWhitespace(String str);
String trimWhitespace(String str);
String trimAllWhitespace(String str);
String delete(String inString, String pattern);
String deleteAny(String inString, String charsToDelete);
String[] trimArrayElements(String[] array);
String uriDecode(String source, Charset charset);
</code>CollectionUtils
Methods to check emptiness of collections and maps, and to test containment.
Operations for merging arrays into collections, merging properties into maps, retrieving the last element, finding matches, and determining common element types.
<code>boolean isEmpty(Collection<?> collection);
boolean isEmpty(Map<?,?> map);
boolean containsInstance(Collection<?> collection, Object element);
boolean contains(Iterator<?> iterator, Object element);
boolean containsAny(Collection<?> source, Collection<?> candidates);
bool hasUniqueObject(Collection<?> collection);
<T> T lastElement(List<T> list);
<T> T lastElement(Set<T> set);
<E> E findFirstMatch(Collection<?> source, Collection<E> candidates);
<T> T findValueOfType(Collection<?> collection, Class<T> type);
Object findValueOfType(Collection<?> collection, Class<?>[] types);
Class<?> findCommonElementType(Collection<?> collection);
</code>File, Resource, and IO Stream Utilities
FileCopyUtils
Read operations: copy file or input stream to byte array, copy reader to string.
Write operations: copy byte array to file, copy between files, copy between streams, and copy between readers/writers.
<code>byte[] copyToByteArray(File in);
byte[] copyToByteArray(InputStream in);
String copyToString(Reader in);
void copy(byte[] in, File out);
int copy(File in, File out);
void copy(byte[] in, OutputStream out);
int copy(InputStream in, OutputStream out);
void copy(Reader in, Writer out);
void copy(String in, Writer out);
</code>ResourceUtils
Determine if a string is a valid URL, obtain a URL, or retrieve a File from a resource location.
Resource types include FileSystemResource, UrlResource, ClassPathResource, and ServletContextResource.
Common resource operations: existence check, obtaining File, URI, URL, InputStream, and description.
<code>static boolean isUrl(String resourceLocation);
static URL getURL(String resourceLocation);
static File getFile(String resourceLocation);
boolean exists();
File getFile();
URI getURI();
URL getURL();
InputStream getInputStream();
String getDescription();
</code>StreamUtils
Input methods for copying byte arrays, streams, and strings with charset.
Output methods for converting streams to byte arrays or strings, and discarding stream content.
<code>void copy(byte[] in, OutputStream out);
int copy(InputStream in, OutputStream out);
void copy(String in, Charset charset, OutputStream out);
long copyRange(InputStream in, OutputStream out, long start, long end);
byte[] copyToByteArray(InputStream in);
String copyToString(InputStream in, Charset charset);
int drain(InputStream in);
</code>Reflection and AOP Utilities
ReflectionUtils
Method discovery, invocation, and accessibility handling.
Field discovery, value retrieval, assignment, and accessibility handling.
Utility methods for checking method characteristics and performing callbacks on fields.
<code>Method findMethod(Class<?> clazz, String name);
Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes);
Method[] getAllDeclaredMethods(Class<?> leafClass);
Constructor<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes);
bool isEqualsMethod(Method method);
bool isHashCodeMethod(Method method);
bool isToStringMethod(Method method);
bool isObjectMethod(Method method);
bool declaresException(Method method, Class<?> exceptionType);
Object invokeMethod(Method method, Object target);
Object invokeMethod(Method method, Object target, Object... args);
void makeAccessible(Method method);
Field findField(Class<?> clazz, String name);
Field findField(Class<?> clazz, String name, Class<?> type);
bool isPublicStaticFinal(Field field);
Object getField(Field field, Object target);
void setField(Field field, Object target, Object value);
void shallowCopyFieldState(Object src, Object dest);
void makeAccessible(Field field);
void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc);
void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc, ReflectionUtils.FieldFilter ff);
void doWithLocalFields(Class<?> clazz, ReflectionUtils.FieldCallback fc);
</code>AopUtils
Determine whether an object is a Spring AOP proxy, JDK dynamic proxy, or CGLIB proxy.
Retrieve the target class of a proxy.
<code>boolean isAopProxy();
bool isJdkDynamicProxy();
bool isCglibProxy();
Class<?> getTargetClass();
</code>AopContext
<code>Object currentProxy();
</code>macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
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.