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.

macrozheng
macrozheng
macrozheng
Master Spring’s Essential Utility Classes: Assert, StringUtils, BeanUtils & More

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 Assert class provides methods to validate conditions and throw IllegalArgumentException when they are not met.

String str = null;
Assert.isNull(str, "str must be null");
Assert.notNull(str, () -> "str must not be null");

1.1 Check for null

Use Assert.isNull or Assert.notNull to enforce nullability.

1.2 Check collections

List<String> list = null;
Assert.notEmpty(list, "list cannot be empty");
Map<String, String> map = null;
Assert.notEmpty(map, "map cannot be empty");

1.3 Check arbitrary conditions

Assert.isTrue(CollectionUtils.isNotEmpty(list), "list cannot be empty");

2. StringUtils

Spring extends JDK string operations with StringUtils.

2.1 Empty check

if (!StringUtils.hasLength("")) {
    System.out.println("String is empty");
}

2.2 Trim all whitespace

@Test
public void testTrimAll() {
    System.out.println("1" + StringUtils.trimAllWhitespace(" 苏三说技术 测试 ") + "1");
}

2.3 Starts/ends with ignore case

@Test
public void testStartsEnds() {
    System.out.println(StringUtils.startsWithIgnoreCase("苏三说技术", "苏三"));
    System.out.println(StringUtils.endsWithIgnoreCase("苏三说技术", "技术"));
}

2.4 Collection to comma‑delimited string

@Test
public void testCollectionToString() {
    List<String> list = new ArrayList<>();
    list.add("a");
    list.add("b");
    list.add("c");
    System.out.println(StringUtils.collectionToCommaDelimitedString(list));
}

3. CollectionUtils

Provides convenient methods for collection handling.

3.1 Check if empty

List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
if (CollectionUtils.isEmpty(list)) {
    System.out.println("Collection is empty");
}

3.2 Check element existence

if (CollectionUtils.contains(list.iterator(), 3)) {
    System.out.println("Element exists");
}

4. ObjectUtils

Offers powerful null‑safe checks for various object types.

@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");
}

4.2 Null‑safe equality

@Test
public void testEquals() {
    String a = "123";
    String b = null;
    System.out.println(ObjectUtils.nullSafeEquals(a, b));
}

4.3 Get identity hash code

@Test
public void testIdentityHex() {
    String a = "123";
    System.out.println(ObjectUtils.getIdentityHexString(a));
}

5. ClassUtils

Utility methods for class metadata.

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

6. BeanUtils

Facilitates JavaBean operations.

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

7. ReflectionUtils

Simplifies reflection tasks.

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

8. Base64Utils

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

9. SerializationUtils

Map<String, String> map = new HashMap<>();
map.put("a", "1");
byte[] data = SerializationUtils.serialize(map);
Object obj = SerializationUtils.deserialize(data);
System.out.println(obj);

10. HttpStatus

Spring’s HttpStatus enum already defines common HTTP response codes, eliminating the need for manual constants.

private int SUCCESS_CODE = 200;
private int ERROR_CODE = 500;
private int NOT_FOUND_CODE = 404;

11. HtmlUtils

@Test
public void testHtmlEscape() {
    String special = "<div id=\"testDiv\">test1;test2</div>";
    String escaped = HtmlUtils.htmlEscape(special);
    System.out.println(escaped);
}
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.

javaspringSpring FrameworkUtility Classes
macrozheng
Written by

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.

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.