Master Spring’s Assert and Utility Classes: Essential Tips for Backend Developers

This article provides a comprehensive overview of Spring's core utility classes—including Assert, ObjectUtils, StringUtils, CollectionUtils, FileCopyUtils, ResourceUtils, StreamUtils, ReflectionUtils, and AOP helpers—detailing their purpose, key methods, and practical code examples for robust backend development.

Java Interview Crash Guide
Java Interview Crash Guide
Java Interview Crash Guide
Master Spring’s Assert and Utility Classes: Essential Tips for Backend Developers

Assert

Assert is a logical check used to verify conditions that should never occur. The Assert keyword was introduced in JDK 1.4 and can be enabled with the JVM parameter -enableassertions. Spring Boot supplies an Assert utility class for data validation.

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)

ObjectUtils

Utility methods for handling objects, arrays, and collections.

// Get class name of an object; returns "null" if the object is null
String nullSafeClassName(Object obj)

// Get hash code of an object; returns 0 if null
int nullSafeHashCode(Object object)

// Convert boolean array to a safe string representation; returns "null" if null
String nullSafeToString(boolean[] array)

// Get identity hash code as a hex string; returns 0 if null
String getIdentityHexString(Object obj)

// Get class name and hash code as a string; returns "" if null
String identityToString(Object obj)

// Similar to toString(), but returns "" if null
String getDisplayString(Object obj)

StringUtils

String validation and manipulation utilities.

// Check if a string is null or empty (""), whitespace is considered non‑empty
boolean isEmpty(Object str)

// Check if a string ends with a suffix, ignoring case
boolean endsWithIgnoreCase(String str, String suffix)

// Check if a string starts with a prefix, ignoring case
boolean startsWithIgnoreCase(String str, String prefix)

// Determine if a string contains any whitespace characters
boolean containsWhitespace(String str)

// Check if a CharSequence has length (Not Empty)
boolean hasLength(CharSequence str)

// Check if a CharSequence contains actual text (Not Blank)
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)

String Operations

// Replace a substring
String replace(String inString, String oldPattern, String newPattern)

// Trim a specific trailing character
String trimTrailingCharacter(String str, char trailingCharacter)

// Trim a specific 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 pattern
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‑encoded string using a charset
String uriDecode(String source, Charset charset)

Path Utilities

// Clean a path, resolving ".."
String cleanPath(String path)

// Extract filename from a path
String getFilename(String path)

// Extract file extension from a path
String getFilenameExtension(String path)

// Compare two paths, handling ".."
boolean pathEquals(String path1, String path2)

// Strip filename extension
String stripFilenameExtension(String path)

// Get the last segment after a separator
String unqualify(String qualifiedName)
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 a collection contains an instance
boolean containsInstance(Collection<?> collection, Object element)

// Check if an iterator contains an element
boolean contains(Iterator<?> iterator, Object element)

// Check if a collection contains any of the given candidates
boolean containsAny(Collection<?> source, Collection<?> candidates)

// Verify that all elements in a collection are unique
boolean hasUniqueObject(Collection<?> collection)

Collection Operations

// Add an object to an array, returning a new array
<A, O extends A> A[] addObjectToArray(A[] array, O obj)

// Convert a primitive array to an Object[]
Object[] toObjectArray(Object source)

// Merge an array into a collection
void mergeArrayIntoCollection(Object array, Collection<E> collection)

// Merge properties into a map
void mergePropertiesIntoMap(Properties props, Map<K,V> map)

// Get the last element of a list or set
<T> T lastElement(List<T> list)
<T> T lastElement(Set<T> set)

// Find the first matching element between two collections
<E> E findFirstMatch(Collection<?> source, Collection<E> candidates)

// Find a value of a specific type in a collection
<T> T findValueOfType(Collection<?> collection, Class<T> type)
Object findValueOfType(Collection<?> collection, Class<?>[] types)

// Determine the common element type in a collection
Class<?> findCommonElementType(Collection<?> collection)

FileCopyUtils

// Read a file into a byte array
byte[] copyToByteArray(File in)

// Read an InputStream into a byte array
byte[] copyToByteArray(InputStream in)

// Write 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)

// Write a byte array to an OutputStream
void copy(byte[] in, OutputStream out)

// Copy an InputStream to an OutputStream
int copy(InputStream in, OutputStream out)

// Copy a Reader to a Writer
int copy(Reader in, Writer out)

// Write a String to a Writer
void copy(String in, Writer out)

ResourceUtils

// Determine if a string is a valid URL
static boolean isUrl(String resourceLocation)

// Get a URL from a resource location
static URL getURL(String resourceLocation)

// Get a File from a resource location (must be a standalone file)
static File getFile(String resourceLocation)

Resource Types

// File system resource (e.g., D:\...)
FileSystemResource

// URL resource (e.g., file://, http://)
UrlResource

// Classpath resource (e.g., classpath:...)
ClassPathResource

// Servlet context resource (e.g., within a JAR or WAR)
ServletContextResource

Resource Operations

// Check if the resource exists
boolean exists()

// Get the underlying File
File getFile()

// Get the URI of the resource
URI getURI()

// Get the URL of the resource
URL getURL()

// Obtain an InputStream for the resource
InputStream getInputStream()

// Get a description of the resource
String getDescription()

StreamUtils

// 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 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)

ReflectionUtils

// Find a method by name
Method findMethod(Class<?> clazz, String name)
Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes)

// Get all declared methods of a class (including inherited)
Method[] getAllDeclaredMethods(Class<?> leafClass)

// Find a constructor and make it accessible
Constructor<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes)

// Check if a method is equals(), hashCode(), or toString()
boolean isEqualsMethod(Method method)
boolean isHashCodeMethod(Method method)
boolean isToStringMethod(Method method)

// Determine if a method is declared on java.lang.Object
boolean isObjectMethod(Method method)

// Check if a method declares a specific exception
boolean declaresException(Method method, Class<?> exceptionType)

Method Invocation

// 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 (bypass Java access checks)
void makeAccessible(Method method)

// Make a constructor accessible
void makeAccessible(Constructor<?> ctor)

Field Access

// Find a field by name
Field findField(Class<?> clazz, String name)
Field findField(Class<?> clazz, String name, Class<?> type)

// Check if a field is public static final
boolean isPublicStaticFinal(Field field)

// Get the value of a field from a target object
Object getField(Field field, Object target)

// Set the value of a field on a target object
void setField(Field field, Object target, Object value)

// Perform a shallow copy of field state from one object to another
void shallowCopyFieldState(Object src, Object dest)

// Make a field accessible (bypass Java access checks)
void makeAccessible(Field field)

// Iterate over fields of a class with a callback
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

// 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()

// Get the target class of a proxy
Class<?> getTargetClass()

AopContext

// Retrieve the current proxy object
Object currentProxy()
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaaopReflectionutilityAssert
Java Interview Crash Guide
Written by

Java Interview Crash Guide

Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.