Stop encapsulating various Util tool classes, this god-level framework is worth having!

Source: ryanc.cc/archives/hutool-java-tools-lib

Today I would like to recommend a very easy-to-use Java tool library. It contains basically all common enterprise-level tool classes. It can avoid reinventing the wheel and save a lot of development time. It is very good and worth knowing and using.

Hutool is homophonic to “muddleheaded”, which means pursuing the state of “taking a confused view of everything, no matter what is lost, no matter what is gained”.

Hutool is a Java toolkit, and it is just a toolkit. It helps us simplify every line of code, reduce every method, and make the Java language “sweet”. Hutool was originally a compilation of the “util” package in my project. Later, it gradually accumulated and added more non-business-related functions, and extensively studied the essence of other open source projects. After its own organization and modification, it finally formed a rich open source tool set.

1. Function

A Java basic tool class that encapsulates JDK methods such as files, streams, encryption and decryption, transcoding, regularization, threads, XML, etc., to form various Util tool classes, and also provides the following components:

  • tool-aop JDK dynamic proxy encapsulation, providing aspect support under non-IOC

  • hutool-bloomFilter Bloom filtering, providing some Hash algorithm Bloom filtering

  • hutool-cache cache

  • hutool-core core, including Bean operations, dates, various Utils, etc.

  • hutool-cron scheduled task module, providing scheduled tasks similar to Crontab expressions

  • hutool-crypto encryption and decryption module

  • hutool-db JDBC encapsulated data operation, based on ActiveRecord idea

  • hutool-dfa multi-keyword search based on DFA model

  • hutool-extra extension module, for third-party packaging (template engine, email, etc.)

  • hutool-http Http client package based on HttpUrlConnection

  • hutool-log automatically identifies the log facade implemented by the log

  • hutool-script script execution package, such as Javascript

  • hutool-setting has a more powerful Setting configuration file and Properties package

  • hutool-system system parameter call encapsulation (JVM information, etc.)

  • hutool-json JSON implementation

  • hutool-captcha image verification code implementation

2. Installation

The maven project can add the following dependencies in pom.xml:

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

3. Simple test

DateUtil

The date and time tool class defines some commonly used date and time operation methods. About Java IO multiplexing: https://www.yoodb.com/java/io/io-multiplexing.html

//Conversion between Date, long and Calendar
//current time
Date date = DateUtil.date();
//Calendar to Date
date = DateUtil.date(Calendar.getInstance());
//Convert timestamp to Date
date = DateUtil.date(System.currentTimeMillis());
//Automatically identify format conversion
String dateStr = "2017-03-01";
date = DateUtil.parse(dateStr);
//Custom format conversion
date = DateUtil.parse(dateStr, "yyyy-MM-dd");
//Format output date
String format = DateUtil.format(date, "yyyy-MM-dd");
//Get the year part
int year = DateUtil.year(date);
//Get the month, counting from 0
int month = DateUtil.month(date);
//Get the start and end time of a certain day
Date beginOfDay = DateUtil.beginOfDay(date);
Date endOfDay = DateUtil.endOfDay(date);
//Calculate the offset date and time
Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
//Calculate the offset between date and time
long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY);

StrUtil

The string tool class defines some commonly used string operation methods.

//Determine whether it is an empty string
String str = "test";
StrUtil.isEmpty(str);
StrUtil.isNotEmpty(str);
//Remove the prefix and suffix of the string
StrUtil.removeSuffix("a.jpg", ".jpg");
StrUtil.removePrefix("a.jpg", "a.");
//Format string
String template = "This is just a placeholder:{}";
String str2 = StrUtil.format(template, "I am a placeholder");
LOGGER.info("/strUtil format:{}", str2);

NumberUtil

Number processing tools can be used for addition, subtraction, multiplication and division operations and judgment types of various types of numbers.

double n1 = 1.234;
double n2 = 1.234;
double result;
//Perform addition, subtraction, multiplication and division operations on float, double and BigDecimal
result = NumberUtil.add(n1, n2);
result = NumberUtil.sub(n1, n2);
result = NumberUtil.mul(n1, n2);
result = NumberUtil.div(n1, n2);
//keep two decimal places
BigDecimal roundNum = NumberUtil.round(n1, 2);
String n3 = "1.234";
//Determine whether it is a number, integer, or floating point number
NumberUtil.isNumber(n3);
NumberUtil.isInteger(n3);
NumberUtil.isDouble(n3);
BeanUtil
JavaBean tool class can be used for conversion between Map and JavaBean objects and copying of object attributes.

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.mapToBean(map, PmsBrand.class, false);
LOGGER.info("beanUtil map to bean:{}", mapBrand);
//Bean property copy
PmsBrand copyBrand = new PmsBrand();
BeanUtil.copyProperties(brand, copyBrand);
LOGGER.info("beanUtil copy properties:{}", copyBrand);

MapUtil

Map operation tool class, which can be used to create Map objects and determine whether the Map is empty.

//Add multiple key-value pairs to the Map
Map<Object, Object> map = MapUtil.of(new String[][]{
    {"key1", "value1"},
    {"key2", "value2"},
    {"key3", "value3"}
});
//Determine whether the Map is empty
MapUtil.isEmpty(map);
MapUtil.isNotEmpty(map);
AnnotationUtil
Annotation tool class can be used to obtain annotations and the values specified in annotations.

//Get the annotation list on the specified class, method, field, and constructor
Annotation[] annotationList = AnnotationUtil.getAnnotations(HutoolController.class, false);
LOGGER.info("annotationUtil annotations:{}", annotationList);
//Get the specified type annotation
Api api = AnnotationUtil.getAnnotation(HutoolController.class, Api.class);
LOGGER.info("annotationUtil api value:{}", api.description());
//Get the value of the specified type annotation
Object annotationValue = AnnotationUtil.getAnnotationValue(HutoolController.class, RequestMapping.class);

SecureUtil

Encryption and decryption tool class, can be used for MD5 encryption.

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

CaptchaUtil Verification code tool class, which can be used to generate graphical verification codes.

//Generate verification code image
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
try {
    request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
    response.setContentType("image/png");//Tell the browser that the output content is a picture
    response.setHeader("Pragma", "No-cache");//Disable browser caching
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expire", 0);
    lineCaptcha.write(response.getOutputStream());
} catch (IOException e) {
    e.printStackTrace();
}

There are many tool types in Hutool, you can refer to the official website: https://www.hutool.cn/

More, useful tools: https://www.yoodb.com/

Of course, there are many other very convenient methods, leave it to you to test! Using the Hutool tool can greatly improve your development efficiency!

c548833eec11f1c28cf261c24fcdf3d7.png

Recommended in the past

Interviewer: Why is Nacos so strong! Tell me about the implementation principle? I was confused. .

If the order is not paid for 30 minutes, it will be automatically canceled. I have five options!

Anyone found using kill -9 to close the program will be fired!

Stop using field injection in SpringBoot!

A Java framework that is 44 times faster than SpringBoot

8c4b577812fbff0e27c37b1d30eb2428.gif