Don't build wheels again. This open source tool class library is easy to use!

Hutool is a small and comprehensive Java tool class library, which helps us simplify every line of code and avoid repeated wheel building. If you need to use some tools, you might as well look in hutool. This paper summarizes 16 commonly used tool classes, hoping to help you!

SpringBoot e-commerce project mall (40k+star) address: https://github.com/macrozheng/mall

install

The installation of Hutool is very simple. In Maven project, you only need to install it in POM Add the following dependencies to XML.

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

Common tools

Using a tool method to replace a piece of complex code and avoid copying and pasting code can greatly improve our development efficiency. Here are my common tools and methods!

Convert

The type conversion tool class is used for the conversion of various types of data. At ordinary times, we often face the problem of type conversion failure. We need to write try catch code. With it, we don't have to write it!

//Convert to string
int a = 1;
String aStr = Convert.toStr(a);
//Converts to an array of the specified type
String[] b = {"1", "2", "3", "4"};
Integer[] bArr = Convert.toIntArray(b);
//Convert to date object
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

The Date time tool class defines some common Date time operation methods. JDK's own Date and Calendar objects are really not easy to use. With them, it's much easier to operate Date and time!

//Conversion between Date, long and Calendar
//current time 
Date date = DateUtil.date();
//Calendar to Date
date = DateUtil.date(Calendar.getInstance());
//Timestamp to Date
date = DateUtil.date(System.currentTimeMillis());
//Automatic recognition 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 part of the year
int year = DateUtil.year(date);
//Get the month, counting from 0
int month = DateUtil.month(date);
//Get the start and end time of a day
Date beginOfDay = DateUtil.beginOfDay(date);
Date endOfDay = DateUtil.endOfDay(date);
//Calculate the date and time after offset
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);

JSONUtil

JSON parsing tool class, which can be used for mutual conversion between objects and JSON.

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

StrUtil

String tool class, which defines some common string operation methods. StrUtil has a shorter name than StringUtil and is more convenient to use!

//Judge whether it is an empty string
String str = "test";
StrUtil.isEmpty(str);
StrUtil.isNotEmpty(str);
//Remove the prefix 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'm a placeholder");
LOGGER.info("/strUtil format:{}", str2);

ClassPathResource

Classpath single resource access class can obtain files under classpath. In Tomcat and other containers, classpath is generally WEB-INF/classes.

//Get the configuration file defined in src/main/resources folder
ClassPathResource resource = new ClassPathResource("generator.properties");
Properties properties = new Properties();
properties.load(resource.getStream());
LOGGER.info("/classPath:{}", properties);

ReflectUtil

Java reflection tool class, which can be used to reflect the methods of obtaining classes and creating objects.

//Get all methods of a class
Method[] methods = ReflectUtil.getMethods(PmsBrand.class);
//Gets the specified method of a class
Method method = ReflectUtil.getMethod(PmsBrand.class, "getId");
//Create objects using reflections
PmsBrand pmsBrand = ReflectUtil.newInstance(PmsBrand.class);
//Method of reflecting execution object
ReflectUtil.invoke(pmsBrand, "setId", 1);

NumberUtil

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

double n1 = 1.234;
double n2 = 1.234;
double result;
//Add / subtract bigfloat
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";
//Judge whether it is a number, integer or floating point number
NumberUtil.isNumber(n3);
NumberUtil.isInteger(n3);
NumberUtil.isDouble(n3);

BeanUtil

JavaBean tool class, which can be used for the mutual conversion between Map and JavaBean objects and the copy of object properties.

PmsBrand brand = new PmsBrand();
brand.setId(1L);
brand.setName("millet");
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 attribute copy
PmsBrand copyBrand = new PmsBrand();
BeanUtil.copyProperties(brand, copyBrand);
LOGGER.info("beanUtil copy properties:{}", copyBrand);

CollUtil

The tool class of collection operation defines some common collection operations.

//Convert array to list
String[] array = new String[]{"a", "b", "c", "d", "e"};
List<String> list = CollUtil.newArrayList(array);
//Join: adds a join symbol when converting an array to a string
String joinStr = CollUtil.join(list, ",");
LOGGER.info("collUtil join:{}", joinStr);
//Converts a concatenated string to a list
List<String> splitList = StrUtil.split(joinStr, ',');
LOGGER.info("collUtil split:{}", splitList);
//Create new Map, Set, List
HashMap<Object, Object> newMap = CollUtil.newHashMap();
HashSet<Object> newHashSet = CollUtil.newHashSet();
ArrayList<Object> newList = CollUtil.newArrayList();
//Judge whether the list is empty
CollUtil.isEmpty(list);

MapUtil

Map operation tool class, which can be used to create map objects and judge 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"}
});
//Judge whether the Map is empty
MapUtil.isEmpty(map);
MapUtil.isNotEmpty(map);

AnnotationUtil

Annotation tool class, which can be used to obtain the value specified in annotation and annotation.

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

SecureUtil

Encryption and decryption tool class, which 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 graphic verification code.

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

Validator

Field Validator, which can verify strings in different formats, such as email, mobile number, IP and other formats.

//Determine whether it is an email address
boolean result = Validator.isEmail("macro@qq.com");
LOGGER.info("Validator isEmail:{}", result);
//Determine whether it is a mobile phone number
result = Validator.isMobile("18911111111");
LOGGER.info("Validator isMobile:{}", result);
//Determine whether it is an IPV4 address
result = Validator.isIpv4("192.168.3.101");
LOGGER.info("Validator isIpv4:{}", result);
//Judge whether it is Chinese character
result = Validator.isChinese("Hello");
LOGGER.info("Validator isChinese:{}", result);
//Judge whether it is an ID number (18 Chinese characters)
result = Validator.isCitizenId("123456");
LOGGER.info("Validator isCitizenId:{}", result);
//Determine whether it is a URL
result = Validator.isUrl("http://www.baidu.com");
LOGGER.info("Validator isUrl:{}", result);
//Determine whether it is a birthday
result = Validator.isBirthday("2020-02-01");
LOGGER.info("Validator isBirthday:{}", result);

DigestUtil

Algorithm tool class, which supports MD5, SHA-256, Bcrypt and other algorithms.

String password = "123456";
//Calculate the MD5 summary value and convert it to hexadecimal string
String result = DigestUtil.md5Hex(password);
LOGGER.info("DigestUtil md5Hex:{}", result);
//Calculate SHA-256 summary value and convert it to hexadecimal string
result = DigestUtil.sha256Hex(password);
LOGGER.info("DigestUtil sha256Hex:{}", result);
//Generate Bcrypt encrypted ciphertext and verify it
String hashPwd = DigestUtil.bcrypt(password);
boolean check = DigestUtil.bcryptCheck(password,hashPwd);
LOGGER.info("DigestUtil bcryptCheck:{}", check);

HttpUtil

Http request tool class, which can initiate GET/POST and other requests.

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

Other tools

There are many tool classes in Hutool, which can be referred to: https://www.hutool.cn/

Project source code address

https://github.com/macrozheng...

This article GitHub https://github.com/macrozheng/mall-learning Already included, welcome to Star!

Tags: Java Back-end IDE

Posted by arjay_comsci on Wed, 11 May 2022 19:17:28 +0300