SpringBoot e-Commerce project mall (20K + STAR) address: github.com/macrozheng/…
Abstract
Hutool is a Java toolkit that helps us simplify each line of code and avoid reinventing the wheel. If you need to use some tools and methods, you can look for them in Hutool. This article introduces common tool classes and methods in Hutool.
The installation
The Maven project adds the following dependencies to pom.xml:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.3</version>
</dependency>
Copy the code
Common Tool Classes
Convert
Type conversion utility class for converting various types of data.
// 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.
// 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
StrUtil
The string utility class defines some common string manipulation methods.
// 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
Get files in the classPath, which is usually web-INF /classes in containers such as Tomcat.
// 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 judgment type.
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 to convert Map and JavaBean objects and copy object attributes.
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
Other Tool classes
Hutool provides a variety of tool classes, for example, www.hutool.cn/
Project source code address
Github.com/macrozheng/…
The public,
Mall project full set of learning tutorials serialized, attention to the public number the first time access.