Tool classes and methods commonly used in Hutool

Keywords: Java github SpringBoot Maven

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

abstract

Hutool is a Java toolkit that helps us simplify every line of code and avoid duplicating wheels. If you need to use some tools and methods, you might as well look in Hutool, it may be. This article will introduce the common tools and methods in Hutool.

install

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>

Common Tool Classes

Convert

Type Conversion Tool Class for the conversion of various types of data.

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

DateUtil

Date and time tool class, defines some commonly used date and time operation methods.

//Conversion among Date, long and Calendar
//current time
Date date = DateUtil.date();
//Calendar to Date
date = DateUtil.date(Calendar.getInstance());
//Time stamp 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");
//Part of the Acquisition Year
int year = DateUtil.year(date);
//Get the month, count from 0
int month = DateUtil.month(date);
//Get the start and end of a day
Date beginOfDay = DateUtil.beginOfDay(date);
Date endOfDay = DateUtil.endOfDay(date);
//Calculate the date and time after migration
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 common string manipulation methods.

//Determine whether it is an empty string
String str = "test";
StrUtil.isEmpty(str);
StrUtil.isNotEmpty(str);
//Remove prefixes and suffixes from strings
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);

ClassPathResource

Get files under classPath. In Tomcat and other containers, classPath is generally WEB-INF/classes.

//Get the configuration file 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);

ReflectUtil

Java Reflector Tool Class, which can be used to reflect the method of acquiring classes and creating 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);
//Method of Reflecting Execution Objects
ReflectUtil.invoke(pmsBrand, "setId", 1);

NumberUtil

The class of digital processing tools can be used for adding, subtracting, multiplying and dividing operations and judging types of various types of numbers.

double n1 = 1.234;
double n2 = 1.234;
double result;
//Add, subtract, multiply and divide 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, an integer, or a floating point number
NumberUtil.isNumber(n3);
NumberUtil.isInteger(n3);
NumberUtil.isDouble(n3);

BeanUtil

Tool classes for JavaBeans can be used to convert Map to JavaBean objects and to copy object attributes.

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

CollUtil

The tool class of set operations defines some common set operations.

//Converting arrays to lists
String[] array = new String[]{"a", "b", "c", "d", "e"};
List<String> list = CollUtil.newArrayList(array);
//join: Add connection symbols when an array is converted to a string
String joinStr = CollUtil.join(list, ",");
LOGGER.info("collUtil join:{}", joinStr);
//Converting a string separated by connection symbols to a list
List<String> splitList = StrUtil.split(joinStr, ',');
LOGGER.info("collUtil split:{}", splitList);
//Create new Map s, Set s, List s
HashMap<Object, Object> newMap = CollUtil.newHashMap();
HashSet<Object> newHashSet = CollUtil.newHashSet();
ArrayList<Object> newList = CollUtil.newArrayList();
//Determine whether the list is empty
CollUtil.isEmpty(list);

MapUtil

Map Operating Tool Class, which can be used to create Map objects and determine whether the Map is empty.

//Add multiple key-value pairs to Map
Map<Object, Object> map = MapUtil.of(new String[][]{
    {"key1", "value1"},
    {"key2", "value2"},
    {"key3", "value3"}
});
//Determine whether a Map is empty
MapUtil.isEmpty(map);
MapUtil.isNotEmpty(map);

AnnotationUtil

Annotation tool class, which can be used to obtain the values specified in the annotations and 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);
//Gets the specified type annotation
Api api = AnnotationUtil.getAnnotation(HutoolController.class, Api.class);
LOGGER.info("annotationUtil api value:{}", api.description());
//Gets 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 graphic verification code.

//Generating Verification Code Pictures
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
try {
    request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
    response.setContentType("image/png");//Tell the browser to output pictures
    response.setHeader("Pragma", "No-cache");//Prohibit browser caching
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expire", 0);
    lineCaptcha.write(response.getOutputStream());
} catch (IOException e) {
    e.printStackTrace();
}

Other Tool Classes

There are many tool classes in Hutool. Please refer to: https://www.hutool.cn/

Project source address

https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-hutool

Public address

mall project In the whole series of learning courses, we pay attention to the first time acquisition of the public number.

Posted by damdempsel on Sun, 22 Sep 2019 04:19:54 -0700