SpringBoot e-commerce project mall (40K + STAR) address: github.com/macrozheng/…

Abstract

Hutool is a small, comprehensive Java tool class library that helps us simplify each line of code and avoid reinventing the wheel. If you need to use any of these classes, look for them in Hutool. This article summarizes 16 commonly used tool classes, hoping to help you!

The installation

Installing Hutool is as simple as adding the following dependencies to POM.xml in the Maven project.

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

Common Tool Classes

Use a tool method instead of a piece of complex code, avoid copy and paste code, can greatly improve our development efficiency, the following introduction to my common tool method!

Convert

Type conversion utility class for converting various types of data. If you want to write a try catch code, you don’t need to write a try catch code.

// Convert to a string
int a = 1;
String aStr = Convert.toStr(a);
// Convert to an array of the specified type
String[] b = {"1"."2"."3"."4"};
Integer[] bArr = Convert.toIntArray(b);
// Convert to a date object
String dateStr = "2017-05-06";
Date date = Convert.toDate(dateStr);
// Convert to a list
String[] strArr = {"a"."b"."c"."d"};
List<String> strList = Convert.toList(String.class, strArr);
Copy the code

DateUtil

The datetime utility class defines some common datetime manipulation methods. Date and Calendar objects in the JDK are really hard to use, so it’s much easier to manipulate dates and times!

// Convert between Date, long, and Calendar
// The current time
Date date = DateUtil.date();
/ / the Calendar Date
date = DateUtil.date(Calendar.getInstance());
// Change the timestamp to Date
date = DateUtil.date(System.currentTimeMillis());
// Automatically recognize format conversion
String dateStr = "2017-03-01";
date = DateUtil.parse(dateStr);
// Custom formatting conversion
date = DateUtil.parse(dateStr, "yyyy-MM-dd");
// Format the output date
String format = DateUtil.format(date, "yyyy-MM-dd");
// Get the year portion
int year = DateUtil.year(date);
// Get the months, counting from 0
int month = DateUtil.month(date);
// Get the start and end times of a 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);
Copy the code

JSONUtil

JSON parsing tool class, which can be used to convert objects to AND from JSON.

PmsBrand brand = new PmsBrand();
brand.setId(1L);
brand.setName("Millet");
brand.setShowStatus(1);
// The object is converted to a 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 is converted to list
brandList = JSONUtil.toList(new JSONArray(jsonListStr), PmsBrand.class);
LOGGER.info("jsonUtil toList:{}", brandList);
Copy the code

StrUtil

The string utility class defines some common string manipulation methods. StrUtil is shorter and easier to use than StringUtil!

// Check for 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 a string
String template = "This is just a placeholder :{}";
String str2 = StrUtil.format(template, "I'm a placeholder.");
LOGGER.info("/strUtil format:{}", str2);
Copy the code

ClassPathResource

ClassPath Single-resource access class, which can obtain files in the ClassPath. In containers such as Tomcat, ClassPath is usually web-INF /classes.

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

ReflectUtil

Java reflection utility class, which can be used to reflect methods that get classes and create objects.

// Get all the methods of a class
Method[] methods = ReflectUtil.getMethods(PmsBrand.class);
// Gets the specified method of a class
Method method = ReflectUtil.getMethod(PmsBrand.class, "getId");
// Use reflection to create objects
PmsBrand pmsBrand = ReflectUtil.newInstance(PmsBrand.class);
// reflect the method of executing the object
ReflectUtil.invoke(pmsBrand, "setId".1);
Copy the code

NumberUtil

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

double n1 = 1.234;
double n2 = 1.234;
double result;
// Add, subtract, multiply and divide float, double, 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";
// Check whether it is a number, integer, or floating point
NumberUtil.isNumber(n3);
NumberUtil.isInteger(n3);
NumberUtil.isDouble(n3);
Copy the code

BeanUtil

JavaBean tool class, which can be used for Map and JavaBean object conversion and object properties copy.

PmsBrand brand = new PmsBrand();
brand.setId(1L);
brand.setName("Millet");
brand.setShowStatus(0);
/ / Bean Map
Map<String, Object> map = BeanUtil.beanToMap(brand);
LOGGER.info("beanUtil bean to map:{}", map);
/ / Map Bean
PmsBrand mapBrand = BeanUtil.mapToBean(map, PmsBrand.class, false);
LOGGER.info("beanUtil map to bean:{}", mapBrand);
// Copy Bean properties
PmsBrand copyBrand = new PmsBrand();
BeanUtil.copyProperties(brand, copyBrand);
LOGGER.info("beanUtil copy properties:{}", copyBrand);
Copy the code

CollUtil

The collection operations utility class defines some common collection operations.

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

MapUtil

Map operation tool class, used to create a Map object 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"}});// Check whether Map is empty
MapUtil.isEmpty(map);
MapUtil.isNotEmpty(map);
Copy the code

AnnotationUtil

Annotation utility class that can be used to get annotations and the values specified in the annotations.

// Gets a list of annotations on the specified class, method, field, constructor
Annotation[] annotationList = AnnotationUtil.getAnnotations(HutoolController.class, false);
LOGGER.info("annotationUtil annotations:{}", annotationList);
// Get 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);
Copy the code

SecureUtil

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

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

CaptchaUtil

Captcha tool class that can be used to generate graphic captcha.

// Generate a captcha image
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200.100);
try {
    request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
    response.setContentType("image/png");// Tell the browser to output as 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();
}
Copy the code

Validator

Field validator can validate strings in different formats, such as email, mobile phone number, IP, and so on.

// Check whether it is an email address
boolean result = Validator.isEmail("[email protected]");
LOGGER.info("Validator isEmail:{}", result);
// Check whether it is a mobile phone number
result = Validator.isMobile("18911111111");
LOGGER.info("Validator isMobile:{}", result);
// Check whether it is an IPV4 address
result = Validator.isIpv4("192.168.3.101");
LOGGER.info("Validator isIpv4:{}", result);
// Check if it is Chinese
result = Validator.isChinese("Hello");
LOGGER.info("Validator isChinese:{}", result);
// Check whether it is id number (18 digits Chinese)
result = Validator.isCitizenId("123456");
LOGGER.info("Validator isCitizenId:{}", result);
// Check whether it is a URL
result = Validator.isUrl("http://www.baidu.com");
LOGGER.info("Validator isUrl:{}", result);
// Check whether it is the birthday
result = Validator.isBirthday("2020-02-01");
LOGGER.info("Validator isBirthday:{}", result);
Copy the code

DigestUtil

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

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

HttpUtil

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

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

Other Tool classes

There are many more classes available in Hutool: www.hutool.cn/

Project source code address

Github.com/macrozheng/…

In this paper, making github.com/macrozheng/… Already included, welcome everyone Star!