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 codeCopy 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.

Int a = 1; String aStr = Convert.toStr(a); // Convert to the specified type array 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); String[] strArr = {"a", "b", "c", "d"}; List<String> strList = Convert.toList(String.class, strArr); Copy the codeCopy 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!

Date = dateutil.date (); //Date = dateutil.date (); Date = dateutil. Date (calendar.getinstance ()); Date = dateutil. Date (system.currentTimemillis ()); String dateStr = "2017-03-01"; date = DateUtil.parse(dateStr); Date = dateutil. parse(dateStr, "YYYY-MM-DD "); String format = dateutil. format(date, "YYYY-MM-DD "); Int year = dateutil. year(date); Int month = dateutil. month(date); BeginOfDay = dateutil. beginOfDay(Date); Date endOfDay = DateUtil.endOfDay(date); Date newDate = dateutil. offset(Date, datefield.day_of_month, 2); // Calculate the offset Date. Long betweenDay = dateutil. between(date, newDate, dateunit.day); long betweenDay = dateutil. between(date, newDate, dateunit.day); Copy the codeCopy 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. Elegantly-named setName (" millet "); brand.setShowStatus(1); Parse (brand).toString(); jsonStr = jsonutil.parse (brand).tostring (); LOGGER.info("jsonUtil parse:{}", jsonStr); 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(); BrandList = jsonUtil.tolist (new JSONArray(jsonListStr), pMSbrand.class); LOGGER.info("jsonUtil toList:{}", brandList); Copy the codeCopy the code

StrUtil

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

String STR = "test"; StrUtil.isEmpty(str); StrUtil.isNotEmpty(str); Strutil. removeSuffix("a.jpg", ".jpg"); StrUtil.removePrefix("a.jpg", "a."); // Format String template = "this is just a placeholder :{}"; String str2 = strutil. format(template, "I am a placeholder "); LOGGER.info("/strUtil format:{}", str2); Copy the codeCopy 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.

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

ReflectUtil

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

Method[] methods = reflectutil.getMethods (pmsbrand.class); Method Method = reflectutil. getMethod(pMSbrand. class, "getId"); // Use reflection to create an object PmsBrand PmsBrand = reflectutil.newinstance (pmsbrand.class); // Reflectutil. invoke(pmsBrand, "setId", 1); Copy the codeCopy 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 float, double, BigDecimal result = numberUtil. add(n1, n2); result = NumberUtil.sub(n1, n2); result = NumberUtil.mul(n1, n2); result = NumberUtil.div(n1, n2); // Reserve two decimal places BigDecimal roundNum = NumberUtil. Round (n1, 2); String n3 = "1.234"; Numberutil. isNumber(n3); NumberUtil.isInteger(n3); NumberUtil.isDouble(n3); Copy the codeCopy 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. Elegantly-named setName (" millet "); brand.setShowStatus(0); Map<String, Object> Map = BeanUtil. BeanToMap (brand); LOGGER.info("beanUtil bean to map:{}", map); MapBrand = BeanUtil. MapToBean (Map, PmsBrand. Class, false); LOGGER.info("beanUtil map to bean:{}", mapBrand); PmsBrand copyBrand = new PmsBrand(); BeanUtil.copyProperties(brand, copyBrand); LOGGER.info("beanUtil copy properties:{}", copyBrand); Copy the codeCopy the code

CollUtil

The collection operations utility class defines some common collection operations.

/ / an array list is converted to a String [] array = new String [] {" a ", "b", "c", "d", "e"}; List<String> list = CollUtil.newArrayList(array); //join: String joinStr = CollUtil. Join (list, ","); LOGGER.info("collUtil join:{}", joinStr); List<String> splitList = strutil.split (joinStr, ','); LOGGER.info("collUtil split:{}", splitList); // create a newMap, Set, List HashMap<Object, Object> newMap = collutil.newhashmap (); HashSet<Object> newHashSet = CollUtil.newHashSet(); ArrayList<Object> newList = CollUtil.newArrayList(); // check whether the list isEmpty collutil. isEmpty(list); Copy the codeCopy the code

MapUtil

Map operation tool class, used to create a Map object and determine whether the Map is empty.

Map<Object, Object> Map = MapUtil. Of (new String[][]{{"key1", "value1"}, {"key2", "value2"}, {"key3", "value3"} }); // check whether Map isEmpty maputil.isempty (Map); MapUtil.isNotEmpty(map); Copy the codeCopy the code

AnnotationUtil

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

/ / get the classes, methods, fields, constructors list the annotations on the Annotation [] annotationList = AnnotationUtil. GetAnnotations (HutoolController. Class, false); LOGGER.info("annotationUtil annotations:{}", annotationList); / / access to specified type annotations Api Api. = AnnotationUtil getAnnotation (HutoolController. Class, Api. Class); LOGGER.info("annotationUtil api value:{}", api.description()); / / get the type annotation value specified Object annotationValue = AnnotationUtil. GetAnnotationValue (HutoolController. Class, RequestMapping. Class); Copy the codeCopy the code

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); Copy the codeCopy the code

CaptchaUtil

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

/ / generated captcha images LineCaptcha LineCaptcha = CaptchaUtil. CreateLineCaptcha (200, 100); try { request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode()); response.setContentType("image/png"); SetHeader ("Pragma", "no-cache "); response.setHeader("Pragma"," no-cache "); Responsetheader (" cache-control ", "no-cache"); response.setHeader(" cache-control ", "no-cache"); response.setDateHeader("Expire", 0); lineCaptcha.write(response.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } Duplicate codeCopy the code

Validator

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

Boolean result = validator. isEmail("[email protected]"); LOGGER.info("Validator isEmail:{}", result); Result = validator. isMobile("18911111111"); LOGGER.info("Validator isMobile:{}", result); Result = validator.isipv4 ("192.168.3.101"); LOGGER.info("Validator isIpv4:{}", result); Result = validator. isChinese(" hello "); LOGGER.info("Validator isChinese:{}", result); // Result = validator. isCitizenId("123456"); // Result = validator. isCitizenId("123456"); LOGGER.info("Validator isCitizenId:{}", result); // Check whether URL result = validator. isUrl("http://www.baidu.com"); LOGGER.info("Validator isUrl:{}", result); Result = Validator. IsBirthday ("2020-02-01"); LOGGER.info("Validator isBirthday:{}", result); Copy the codeCopy the code

DigestUtil

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

String password = "123456"; String result = digestutil.md5hex (password); // Calculate the MD5 digest value and convert it to a hexadecimal String. LOGGER.info("DigestUtil md5Hex:{}", result); // Calculate the sha-256 digest value and convert it to a hexadecimal string result = digestutil.sha256hex (password); LOGGER.info("DigestUtil sha256Hex:{}", result); HashPwd = digestUtil. Bcrypt (password); boolean check = DigestUtil.bcryptCheck(password,hashPwd); LOGGER.info("DigestUtil bcryptCheck:{}", check); Copy the codeCopy 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 codeCopy the code

Other Tool classes

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