Why You Should Stop Reinventing Utility Classes and Use Hutool (or Guava) Instead

The article introduces the open‑source Java utility library Hutool, compares it with Guava, lists its modules, shows how to install it via Maven, and provides concrete code examples for HTTP requests, random codes, date handling, string manipulation, number operations, map utilities, encryption, captcha generation, and data desensitization, demonstrating how it can reduce boiler‑plate and speed up development.

Shepherd Advanced Notes
Shepherd Advanced Notes
Shepherd Advanced Notes
Why You Should Stop Reinventing Utility Classes and Use Hutool (or Guava) Instead

Introduction

The author previously covered Google’s open‑source Java core library Guava and now presents Hutool, a Chinese‑origin Java utility library that bundles common enterprise‑level tools to avoid reinventing utility classes and to save development time.

Features

Hutool wraps many JDK APIs (file, stream, encryption, encoding, regex, threading, XML, etc.) into dedicated Util classes. The library is organized into modules, each providing a specific capability:

hutool-aop : JDK dynamic‑proxy wrapper offering aspect support without an IoC container.

hutool-bloomFilter : Bloom filter implementation with several hash algorithms.

hutool-cache : Simple cache implementation.

hutool-core : Core utilities such as Bean operations, date handling, and generic helpers.

hutool-cron : Cron‑style scheduling based on Crontab expressions.

hutool-crypto : Symmetric, asymmetric, and digest algorithm wrappers.

hutool-db : JDBC wrapper following the ActiveRecord pattern.

hutool-dfa : Multi‑keyword search based on DFA models.

hutool-extra : Extensions for third‑party integrations (template engines, mail, servlet, QR code, Emoji, FTP, word segmentation, etc.).

hutool-http : Http client built on HttpUrlConnection that simplifies HTTPS, file upload, and cookie handling.

hutool-log : Auto‑detecting logging façade.

hutool-script : Script execution wrapper (e.g., JavaScript).

hutool-setting : Enhanced configuration file and properties handling.

hutool-system : JVM and system‑parameter utilities.

hutool-json : JSON utilities.

hutool-captcha : Image captcha generation.

hutool-poi : POI‑based Excel and Word helpers.

hutool-socket : NIO/AIO socket wrapper.

hutool-jwt : JSON Web Token implementation.

Installation

Add the following dependency to a Maven pom.xml:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>${hutool.version}</version>
</dependency>

Common Utility Examples

HTTP Requests

Hutool‑http wraps HttpUrlConnection to make GET and POST calls concise.

GET request:

// GET request
String content = HttpUtil.get(url);

POST request with parameters:

// POST request
HashMap<String, Object> param = new HashMap<>();
param.put("city", "西安");
String result = HttpUtil.post("www.javacn.site", param);

Random Verification Code

Generate a 4‑digit uppercase random string:

// Generate 4‑digit random verification code
String verificationCode = RandomUtil.randomStringUpper(4);

DateUtil

DateUtil provides conversion, formatting, and calculation utilities for Date, Calendar, and timestamps.

// Convert between Date, long, Calendar
Date date = DateUtil.date();
date = DateUtil.date(Calendar.getInstance());
date = DateUtil.date(System.currentTimeMillis());
// Parse and format
String dateStr = "2017-03-01";
date = DateUtil.parse(dateStr);
date = DateUtil.parse(dateStr, "yyyy-MM-dd");
String format = DateUtil.format(date, "yyyy-MM-dd");
// Extract parts
int year = DateUtil.year(date);
int month = DateUtil.month(date); // 0‑based
Date beginOfDay = DateUtil.beginOfDay(date);
Date endOfDay = DateUtil.endOfDay(date);
// Offset and between
Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY);

StrUtil

String utilities for emptiness checks, prefix/suffix removal, and formatting.

String str = "test";
StrUtil.isEmpty(str);
StrUtil.isNotEmpty(str);
StrUtil.removeSuffix("a.jpg", ".jpg");
StrUtil.removePrefix("a.jpg", "a.");
String template = "这只是个占位符:{}";
String result = StrUtil.format(template, "我是占位符");
LOGGER.info("/strUtil format:{}", result);

NumberUtil

Arithmetic and type‑checking for primitive numbers and BigDecimal:

double n1 = 1.234;
double n2 = 1.234;
double sum = NumberUtil.add(n1, n2);
double diff = NumberUtil.sub(n1, n2);
double prod = NumberUtil.mul(n1, n2);
double quot = NumberUtil.div(n1, n2);
BigDecimal roundNum = NumberUtil.round(n1, 2);
String n3 = "1.234";
NumberUtil.isNumber(n3);
NumberUtil.isInteger(n3);
NumberUtil.isDouble(n3);

MapUtil

Convenient map creation and emptiness checks:

Map<Object, Object> map = MapUtil.of(new String[][]{
    {"key1", "value1"},
    {"key2", "value2"},
    {"key3", "value3"}
});
MapUtil.isEmpty(map);
MapUtil.isNotEmpty(map);

SecureUtil

MD5 hashing example:

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

CaptchaUtil

Generate a line captcha image and write it to the HTTP response:

LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
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());

Data Desensitization

Hutool provides ready‑made methods to mask sensitive information such as ID numbers, phone numbers, addresses, etc.

// Mask ID card number, hide characters from index 1 to 2
DesensitizedUtil.idCardNum("51343620000320711X", 1, 2);
// Mask a mobile phone number (default pattern)
DesensitizedUtil.mobilePhone("18049531999");
// Mask a password, keeping only length information
DesensitizedUtil.password("1234567890");

Further Resources

For a complete list of utilities, visit the official site: https://www.hutool.cn/

The library contains many additional methods; readers are encouraged to explore them to further improve development efficiency.

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.

JavaHTTPHutoolCode examplesdata-desensitizationDateUtilUtility Library
Shepherd Advanced Notes
Written by

Shepherd Advanced Notes

Dedicated to sharing advanced Java technical insights, daily work snippets, and the power of persistent effort.

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.