Master Spring’s Essential Utility Classes: Assert, StringUtils, BeanUtils & More
This comprehensive guide walks you through the most useful Spring framework utility classes—including Assert, StringUtils, CollectionUtils, ObjectUtils, ClassUtils, BeanUtils, ReflectionUtils, Base64Utils, SerializationUtils, HttpStatus, and HtmlUtils—showing practical code examples and explaining when and how to use each to streamline Java backend development.
Introduction
Many developers look for ready‑made tools to boost productivity, and Spring offers a rich set of utility classes that cover assertions, string handling, collection checks, object operations, class introspection, bean manipulation, reflection, encoding, serialization, HTTP status handling, and HTML escaping.
1. Assert
The
Assertclass provides methods to validate conditions and throw
IllegalArgumentExceptionwhen they are not met.
<code>String str = null;
Assert.isNull(str, "str must be null");
Assert.notNull(str, () -> "str must not be null");</code>1.1 Check for null
Use
Assert.isNullor
Assert.notNullto enforce nullability.
1.2 Check collections
<code>List<String> list = null;
Assert.notEmpty(list, "list cannot be empty");
Map<String, String> map = null;
Assert.notEmpty(map, "map cannot be empty");</code>1.3 Check arbitrary conditions
<code>Assert.isTrue(CollectionUtils.isNotEmpty(list), "list cannot be empty");</code>2. StringUtils
Spring extends JDK string operations with
StringUtils.
2.1 Empty check
<code>if (!StringUtils.hasLength("")) {
System.out.println("String is empty");
}</code>2.2 Trim all whitespace
<code>@Test
public void testTrimAll() {
System.out.println("1" + StringUtils.trimAllWhitespace(" 苏三说技术 测试 ") + "1");
}</code>2.3 Starts/ends with ignore case
<code>@Test
public void testStartsEnds() {
System.out.println(StringUtils.startsWithIgnoreCase("苏三说技术", "苏三"));
System.out.println(StringUtils.endsWithIgnoreCase("苏三说技术", "技术"));
}</code>2.4 Collection to comma‑delimited string
<code>@Test
public void testCollectionToString() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
System.out.println(StringUtils.collectionToCommaDelimitedString(list));
}</code>3. CollectionUtils
Provides convenient methods for collection handling.
3.1 Check if empty
<code>List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
if (CollectionUtils.isEmpty(list)) {
System.out.println("Collection is empty");
}</code>3.2 Check element existence
<code>if (CollectionUtils.contains(list.iterator(), 3)) {
System.out.println("Element exists");
}</code>4. ObjectUtils
Offers powerful null‑safe checks for various object types.
<code>@Test
public void testObjectUtils() {
String a = "123";
Integer b = new Integer(1);
List<String> c = new ArrayList<>();
c.add(a);
Map<String, String> e = new HashMap<>();
e.put(a, a);
Optional<String> f = Optional.of(a);
if (!ObjectUtils.isEmpty(a)) System.out.println("a not empty");
if (!ObjectUtils.isEmpty(b)) System.out.println("b not empty");
if (!ObjectUtils.isEmpty(c)) System.out.println("c not empty");
if (!ObjectUtils.isEmpty(e)) System.out.println("e not empty");
if (!ObjectUtils.isEmpty(f)) System.out.println("f not empty");
}</code>4.2 Null‑safe equality
<code>@Test
public void testEquals() {
String a = "123";
String b = null;
System.out.println(ObjectUtils.nullSafeEquals(a, b));
}</code>4.3 Get identity hash code
<code>@Test
public void testIdentityHex() {
String a = "123";
System.out.println(ObjectUtils.getIdentityHexString(a));
}</code>5. ClassUtils
Utility methods for class metadata.
<code>Class<?>[] interfaces = ClassUtils.getAllInterfaces(new User());
String pkg = ClassUtils.getPackageName(User.class);
System.out.println(pkg);
System.out.println(ClassUtils.isInnerClass(User.class));
System.out.println(ClassUtils.isCglibProxy(new User()));
</code>6. BeanUtils
Facilitates JavaBean operations.
<code>User user1 = new User();
user1.setId(1L);
user1.setName("Example");
User user2 = new User();
BeanUtils.copyProperties(user1, user2);
System.out.println(user2);
User user = BeanUtils.instantiateClass(User.class);
Method m = BeanUtils.findDeclaredMethod(User.class, "getId");
System.out.println(m.getName());
</code>7. ReflectionUtils
Simplifies reflection tasks.
<code>Method method = ReflectionUtils.findMethod(User.class, "getId");
Field field = ReflectionUtils.findField(User.class, "id");
ReflectionUtils.invokeMethod(method, bean, param);
System.out.println(ReflectionUtils.isPublicStaticFinal(field));
System.out.println(ReflectionUtils.isEqualsMethod(method));
</code>8. Base64Utils
<code>String str = "abc";
String encode = new String(Base64Utils.encode(str.getBytes()));
System.out.println("Encoded: " + encode);
String decode = new String(Base64Utils.decode(encode.getBytes()), "utf8");
System.out.println("Decoded: " + decode);
</code>9. SerializationUtils
<code>Map<String, String> map = new HashMap<>();
map.put("a", "1");
byte[] data = SerializationUtils.serialize(map);
Object obj = SerializationUtils.deserialize(data);
System.out.println(obj);
</code>10. HttpStatus
Spring’s
HttpStatusenum already defines common HTTP response codes, eliminating the need for manual constants.
<code>private int SUCCESS_CODE = 200;
private int ERROR_CODE = 500;
private int NOT_FOUND_CODE = 404;
</code>11. HtmlUtils
<code>@Test
public void testHtmlEscape() {
String special = "<div id=\"testDiv\">test1;test2</div>";
String escaped = HtmlUtils.htmlEscape(special);
System.out.println(escaped);
}
</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.