Backend Development 15 min read

Boost Java Development with Hutool: 17 Essential Utility Classes Explained

This article introduces the Hutool Java utility library, showing how to install it via Maven and demonstrating 17 commonly used utility classes with code examples that simplify type conversion, date handling, JSON processing, string manipulation, reflection, encryption, validation, and more for backend developers.

macrozheng
macrozheng
macrozheng
Boost Java Development with Hutool: 17 Essential Utility Classes Explained
Hutool is a small yet comprehensive Java utility library that helps simplify code and avoid reinventing the wheel; this article summarizes 17 commonly used utility classes.

Installation

Hutool can be added to a Maven project by including the following dependency in

pom.xml

:

<code>&lt;dependency&gt;
    &lt;groupId&gt;cn.hutool&lt;/groupId&gt;
    &lt;artifactId&gt;hutool-all&lt;/artifactId&gt;
    &lt;version&gt;${hutool.version}&lt;/version&gt;
&lt;/dependency&gt;
</code>

Common Utility Classes

Using a utility method instead of a block of complex code and avoiding copy‑paste can greatly improve development efficiency; below are the most frequently used methods.

Convert

The conversion utility class handles various type conversions, eliminating the need for repetitive try‑catch blocks.

<code>// Convert to string
int a = 1;
String aStr = Convert.toStr(a);
// Convert to int array
String[] b = {"1", "2", "3", "4"};
Integer[] bArr = Convert.toIntArray(b);
// Convert to date
String dateStr = "2017-05-06";
Date date = Convert.toDate(dateStr);
// Convert to list
String[] strArr = {"a", "b", "c", "d"};
List<String> strList = Convert.toList(String.class, strArr);
</code>

DateUtil

Date and time utility class provides convenient methods for common date operations, simplifying the cumbersome JDK Date and Calendar APIs.

<code>// Current date
Date date = DateUtil.date();
// Calendar to Date
date = DateUtil.date(Calendar.getInstance());
// Timestamp to Date
date = DateUtil.date(System.currentTimeMillis());
// Parse string to date
String dateStr = "2017-03-01";
date = DateUtil.parse(dateStr);
// Custom format parsing
date = DateUtil.parse(dateStr, "yyyy-MM-dd");
// Format date to string
String format = DateUtil.format(date, "yyyy-MM-dd");
// Get year and month
int year = DateUtil.year(date);
int month = DateUtil.month(date);
// Begin and end of day
Date beginOfDay = DateUtil.beginOfDay(date);
Date endOfDay = DateUtil.endOfDay(date);
// Offset date
Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
// Calculate difference in days
long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY);
</code>

JSONUtil

JSON parsing utility class enables conversion between objects and JSON strings.

<code>PmsBrand brand = new PmsBrand();
brand.setId(1L);
brand.setName("Xiaomi");
brand.setShowStatus(1);
// Object to JSON string
String jsonStr = JSONUtil.parse(brand).toString();
LOGGER.info("jsonUtil parse:{}", jsonStr);
// JSON string to object
PmsBrand brandBean = JSONUtil.toBean(jsonStr, PmsBrand.class);
LOGGER.info("jsonUtil toBean:{}", brandBean);
// List conversion
List<PmsBrand> brandList = new ArrayList<>();
brandList.add(brand);
String jsonListStr = JSONUtil.parse(brandList).toString();
brandList = JSONUtil.toList(new JSONArray(jsonListStr), PmsBrand.class);
LOGGER.info("jsonUtil toList:{}", brandList);
</code>

StrUtil

String utility class offers concise methods for common string operations.

<code>// Check empty
String str = "test";
StrUtil.isEmpty(str);
StrUtil.isNotEmpty(str);
// Remove suffix/prefix
StrUtil.removeSuffix("a.jpg", ".jpg");
StrUtil.removePrefix("a.jpg", "a.");
// Format string
String template = "This is a placeholder:{}";
String str2 = StrUtil.format(template, "I am the placeholder");
LOGGER.info("/strUtil format:{}", str2);
</code>

ClassPathResource

Accesses resources on the classpath, useful for loading configuration files.

<code>// Load generator.properties from src/main/resources
ClassPathResource resource = new ClassPathResource("generator.properties");
Properties properties = new Properties();
properties.load(resource.getStream());
LOGGER.info("/classPath:{}", properties);
</code>

ReflectUtil

Reflection utility class simplifies method retrieval, object instantiation, and method invocation.

<code>// Get all methods of a class
Method[] methods = ReflectUtil.getMethods(PmsBrand.class);
// Get specific method
Method method = ReflectUtil.getMethod(PmsBrand.class, "getId");
// Create instance via reflection
PmsBrand pmsBrand = ReflectUtil.newInstance(PmsBrand.class);
// Invoke method
ReflectUtil.invoke(pmsBrand, "setId", 1);
</code>

NumberUtil

Number utility class provides arithmetic operations and type checks for various numeric types.

<code>double n1 = 1.234;
double n2 = 1.234;
double result;
result = NumberUtil.add(n1, n2);
result = NumberUtil.sub(n1, n2);
result = NumberUtil.mul(n1, n2);
result = NumberUtil.div(n1, n2);
BigDecimal roundNum = NumberUtil.round(n1, 2);
String n3 = "1.234";
NumberUtil.isNumber(n3);
NumberUtil.isInteger(n3);
NumberUtil.isDouble(n3);
</code>

BeanUtil

JavaBean utility class enables conversion between maps and beans and property copying.

<code>PmsBrand brand = new PmsBrand();
brand.setId(1L);
brand.setName("Xiaomi");
brand.setShowStatus(0);
// Bean to Map
Map<String, Object> map = BeanUtil.beanToMap(brand);
LOGGER.info("beanUtil bean to map:{}", map);
// Map to Bean
PmsBrand mapBrand = BeanUtil.toBean(map, PmsBrand.class);
LOGGER.info("beanUtil map to bean:{}", mapBrand);
// Copy properties
PmsBrand copyBrand = new PmsBrand();
BeanUtil.copyProperties(brand, copyBrand);
LOGGER.info("beanUtil copy properties:{}", copyBrand);
</code>

CollUtil

Collection utility class offers convenient methods for handling arrays, lists, sets, and other collections.

<code>// Array to List
String[] array = new String[]{"a", "b", "c", "d", "e"};
List<String> list = CollUtil.newArrayList(array);
// Join list to string
String joinStr = CollUtil.join(list, ",");
LOGGER.info("collUtil join:{}", joinStr);
// Split string back to list
List<String> splitList = StrUtil.split(joinStr, ',');
LOGGER.info("collUtil split:{}", splitList);
// Create new Set and List
HashSet<Object> newHashSet = CollUtil.newHashSet();
ArrayList<Object> newList = CollUtil.newArrayList();
// Check if list is empty
CollUtil.isEmpty(list);
</code>

MapUtil

Map utility class simplifies map creation and emptiness checks.

<code>// Create map with multiple entries
Map<Object, Object> map = MapUtil.of(new String[][]{
    {"key1", "value1"},
    {"key2", "value2"},
    {"key3", "value3"}
});
// Check map emptiness
MapUtil.isEmpty(map);
MapUtil.isNotEmpty(map);
</code>

AnnotationUtil

Annotation utility class retrieves annotations and their values from classes, methods, fields, etc.

<code>// Get all annotations on a class
Annotation[] annotationList = AnnotationUtil.getAnnotations(HutoolController.class, false);
LOGGER.info("annotationUtil annotations:{}", annotationList);
// Get specific annotation
Api api = AnnotationUtil.getAnnotation(HutoolController.class, Api.class);
LOGGER.info("annotationUtil api value:{}", api.description());
// Get annotation value
Object annotationValue = AnnotationUtil.getAnnotationValue(HutoolController.class, RequestMapping.class);
</code>

SecureUtil

Encryption utility class provides MD5 hashing.

<code>String str = "123456";
String md5Str = SecureUtil.md5(str);
LOGGER.info("secureUtil md5:{}", md5Str);
</code>

BCrypt

BCrypt utility class offers BCrypt hashing and verification, used by Spring Security.

<code>String str = "123456";
String bCryptStr = BCrypt.hashpw(str);
LOGGER.info("bCrypt hashpw:{}", bCryptStr);
boolean result = BCrypt.checkpw(str, bCryptStr);
LOGGER.info("bCrypt checkpw:{}", result);
</code>

CaptchaUtil

Captcha utility class generates image captchas.

<code>LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
try {
    request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
    response.setContentType("image/png");
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expire", 0);
    lineCaptcha.write(response.getOutputStream());
} catch (IOException e) {
    e.printStackTrace();
}
</code>

Validator

Validator utility class checks formats such as email, mobile, IP, Chinese characters, ID numbers, URLs, and birthdays.

<code>boolean result = Validator.isEmail("[email protected]");
LOGGER.info("Validator isEmail:{}", result);
result = Validator.isMobile("18911111111");
LOGGER.info("Validator isMobile:{}", result);
result = Validator.isIpv4("192.168.3.101");
LOGGER.info("Validator isIpv4:{}", result);
result = Validator.isChinese("你好");
LOGGER.info("Validator isChinese:{}", result);
result = Validator.isCitizenId("123456");
LOGGER.info("Validator isCitizenId:{}", result);
result = Validator.isUrl("http://www.baidu.com");
LOGGER.info("Validator isUrl:{}", result);
result = Validator.isBirthday("2020-02-01");
LOGGER.info("Validator isBirthday:{}", result);
</code>

DigestUtil

Digest utility class supports MD5, SHA‑256, and Bcrypt algorithms.

<code>String password = "123456";
String result = DigestUtil.md5Hex(password);
LOGGER.info("DigestUtil md5Hex:{}", result);
result = DigestUtil.sha256Hex(password);
LOGGER.info("DigestUtil sha256Hex:{}", result);
String hashPwd = DigestUtil.bcrypt(password);
boolean check = DigestUtil.bcryptCheck(password, hashPwd);
LOGGER.info("DigestUtil bcryptCheck:{}", check);
</code>

HttpUtil

HTTP request utility class can send GET/POST requests.

<code>String response = HttpUtil.get("http://localhost:8080/hutool/covert");
LOGGER.info("HttpUtil get:{}", response);
</code>

Other Utility Classes

Hutool provides many more utility classes; refer to the official site for the full list.

https://www.hutool.cn/

Project Source Code

Source code for this tutorial is available at:

https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-hutool

Javabackend developmentMavenHutoolcode examplesUtility Library
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

login 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.