Master Hutool: Essential Java Utility Classes and How to Use Them
This guide introduces the Hutool Java utility library, showing how to install it via Maven and demonstrating key utility classes such as Convert, DateUtil, StrUtil, ReflectUtil, and more with practical code examples for backend development.
Hutool is a Java utility library that helps simplify code and avoid reinventing the wheel. It provides many ready‑to‑use methods; this article introduces its most common utility classes and usage examples.
Installation
For Maven projects, add the following dependency to
pom.xml:
<code><dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.3</version>
</dependency></code>Common Utility Classes
Convert
Type conversion utilities for various data types.
<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 utilities offering common operations.
<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 (auto format)
String dateStr = "2017-03-01";
date = DateUtil.parse(dateStr);
// Parse with custom format
date = DateUtil.parse(dateStr, "yyyy-MM-dd");
// Format date
String format = DateUtil.format(date, "yyyy-MM-dd");
// Year, month (0‑based)
int year = DateUtil.year(date);
int month = DateUtil.month(date);
// Start/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);
// Difference in days
long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY);
</code>StrUtil
String utilities for common manipulations.
<code>// Empty check
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 = "这只是个占位符:{}";
String str2 = StrUtil.format(template, "我是占位符");
LOGGER.info("/strUtil format:{}", str2);
</code>ClassPathResource
Load files from the classpath (e.g.,
WEB-INF/classesin Tomcat).
<code>// Load a properties file 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 utilities for accessing methods and creating objects.
<code>// Get all methods of a class
Method[] methods = ReflectUtil.getMethods(PmsBrand.class);
// Get a specific method
Method method = ReflectUtil.getMethod(PmsBrand.class, "getId");
// Create an instance via reflection
PmsBrand pmsBrand = ReflectUtil.newInstance(PmsBrand.class);
// Invoke a method
ReflectUtil.invoke(pmsBrand, "setId", 1);
</code>NumberUtil
Number utilities for arithmetic and type checks.
<code>double n1 = 1.234;
double n2 = 1.234;
double result;
// Arithmetic operations
result = NumberUtil.add(n1, n2);
result = NumberUtil.sub(n1, n2);
result = NumberUtil.mul(n1, n2);
result = NumberUtil.div(n1, n2);
// Round to 2 decimal places
BigDecimal roundNum = NumberUtil.round(n1, 2);
String n3 = "1.234";
// Type checks
NumberUtil.isNumber(n3);
NumberUtil.isInteger(n3);
NumberUtil.isDouble(n3);
</code>BeanUtil
Utilities for converting between JavaBeans and Maps and copying properties.
<code>PmsBrand brand = new PmsBrand();
brand.setId(1L);
brand.setName("小米");
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.mapToBean(map, PmsBrand.class, false);
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 utilities for common operations.
<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 collections
HashMap<Object, Object> newMap = CollUtil.newHashMap();
HashSet<Object> newHashSet = CollUtil.newHashSet();
ArrayList<Object> newList = CollUtil.newArrayList();
// Check if empty
CollUtil.isEmpty(list);
</code>MapUtil
Map utilities for creation and emptiness checks.
<code>// Create a map with multiple entries
Map<Object, Object> map = MapUtil.of(new String[][]{
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}
});
// Emptiness checks
MapUtil.isEmpty(map);
MapUtil.isNotEmpty(map);
</code>AnnotationUtil
Annotation utilities for retrieving annotations and their values.
<code>// Get all annotations on a class
Annotation[] annotationList = AnnotationUtil.getAnnotations(HutoolController.class, false);
LOGGER.info("annotationUtil annotations:{}", annotationList);
// Get a 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 utilities, e.g., MD5 hashing.
<code>// MD5 hash
String str = "123456";
String md5Str = SecureUtil.md5(str);
LOGGER.info("secureUtil md5:{}", md5Str);
</code>CaptchaUtil
Utility for generating image captchas.
<code>// Create line captcha
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
try {
request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
response.setContentType("image/png"); // output as image
response.setHeader("Pragma", "No-cache"); // prevent caching
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expire", 0);
lineCaptcha.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
</code>Other Utility Classes
Hutool contains many more utilities; see the official site for the full list.
Project Source Code
https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-hutool
Recommended Reading
Java 8 has been out for a long time – explore the Stream API?
SpringBoot Admin 2.0 detailed guide
Git operations in IDEA – this article is enough!
Set up your own Git repository in 10 minutes
Those years we’ve seen Java backend chaos
My GitHub open‑source project, from 0 to 20,000 stars!
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.