Boost Java Development with Hutool: 16 Essential Utility Classes Explained

This article introduces the Hutool Java utility library, showing how to install it via Maven and demonstrating 16 frequently used utility classes—including Convert, DateUtil, JSONUtil, StrUtil, and more—with concise code examples that illustrate simplifying common development tasks.

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

Installation

Adding Hutool to a Maven project only requires adding the following dependency to pom.xml:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.4.0</version>
</dependency>

Common Utility Classes

Convert

Provides convenient type conversion methods, eliminating the need for repetitive try‑catch blocks.

// Convert to String
int a = 1;
String aStr = Convert.toStr(a);
// Convert to specific type 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);

DateUtil

Offers a rich set of date‑time operations, making handling dates far easier than using JDK's Date and Calendar.

// Current time
Date date = DateUtil.date();
// Calendar to Date
date = DateUtil.date(Calendar.getInstance());
// Timestamp to Date
date = DateUtil.date(System.currentTimeMillis());
// Auto‑detect format parsing
String dateStr = "2017-03-01";
date = DateUtil.parse(dateStr);
// Custom format parsing
date = DateUtil.parse(dateStr, "yyyy-MM-dd");
// Format output
String format = DateUtil.format(date, "yyyy-MM-dd");
// Year and month
int year = DateUtil.year(date);
int month = DateUtil.month(date);
// Begin/end of day
Date beginOfDay = DateUtil.beginOfDay(date);
Date endOfDay = DateUtil.endOfDay(date);
// Offset calculation
Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
// Between days
long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY);

JSONUtil

Handles conversion between objects and JSON strings.

PmsBrand brand = new PmsBrand();
brand.setId(1L);
brand.setName("小米");
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<PmsBrand> brandList = new ArrayList<>();
brandList.add(brand);
String jsonListStr = JSONUtil.parse(brandList).toString();
// JSON string to list
brandList = JSONUtil.toList(new JSONArray(jsonListStr), PmsBrand.class);
LOGGER.info("jsonUtil toList:{}", brandList);

StrUtil

Provides concise string manipulation methods.

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

ClassPathResource

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

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

ReflectUtil

Facilitates reflection operations such as retrieving methods and creating instances.

// All methods of a class
Method[] methods = ReflectUtil.getMethods(PmsBrand.class);
// 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);

NumberUtil

Performs arithmetic and numeric checks on various number types.

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

BeanUtil

Converts between JavaBeans and Maps and copies bean properties.

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

CollUtil

Offers common collection operations such as conversion, joining, and creation of new collections.

// 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 emptiness
CollUtil.isEmpty(list);

MapUtil

Simplifies creation and emptiness checks of maps.

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

AnnotationUtil

Retrieves annotations and their values from classes, methods, fields, etc.

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

SecureUtil

Provides simple MD5 hashing.

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

CaptchaUtil

Generates image captchas.

// Create line captcha
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();
}

Validator

Validates common data formats such as email, phone, IP, etc.

// Email validation
boolean result = Validator.isEmail("[email protected]");
LOGGER.info("Validator isEmail:{}", result);
// Mobile validation
result = Validator.isMobile("18911111111");
LOGGER.info("Validator isMobile:{}", result);
// IPv4 validation
result = Validator.isIpv4("192.168.3.101");
LOGGER.info("Validator isIpv4:{}", result);
// Chinese characters validation
result = Validator.isChinese("你好");
LOGGER.info("Validator isChinese:{}", result);
// ID card validation
result = Validator.isCitizenId("123456");
LOGGER.info("Validator isCitizenId:{}", result);
// URL validation
result = Validator.isUrl("http://www.baidu.com");
LOGGER.info("Validator isUrl:{}", result);
// Birthday validation
result = Validator.isBirthday("2020-02-01");
LOGGER.info("Validator isBirthday:{}", result);

DigestUtil

Supports various digest algorithms including MD5, SHA‑256, and Bcrypt.

// MD5 hex
String result = DigestUtil.md5Hex(password);
LOGGER.info("DigestUtil md5Hex:{}", result);
// SHA‑256 hex
result = DigestUtil.sha256Hex(password);
LOGGER.info("DigestUtil sha256Hex:{}", result);
// Bcrypt hash and verification
String hashPwd = DigestUtil.bcrypt(password);
boolean check = DigestUtil.bcryptCheck(password, hashPwd);
LOGGER.info("DigestUtil bcryptCheck:{}", check);

HttpUtil

Facilitates HTTP requests such as GET and POST.

String response = HttpUtil.get("http://localhost:8080/hutool/covert");
LOGGER.info("HttpUtil get:{}", response);
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.

JavaBackend Developmenthutoolutilitycode
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.