Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the components of the Hutool tool

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "what components does the Hutool tool include", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what components the Hutool tool contains.

Brief introduction

Hutool is a small and comprehensive Java tool class library, encapsulated by static methods, reduce the learning cost of related API, improve work efficiency, make Java have functional language-like elegance, so that Java language can also be "sweet".

The tools and methods in Hutool come from the meticulous craftsmanship of each user. It covers all aspects of the underlying code of Java development. It is not only a sharp tool for solving small problems in large-scale project development, but also an efficient role in small projects.

Hutool is a friendly alternative to the "util" package in the project. It saves developers time to encapsulate common classes and tools in the project, makes developers focus on business, and minimizes the bug caused by imperfect encapsulation.

The Origin of the name Hutool

Hutool = Hu + tool, which is the open source library after the stripping of the underlying code of the original company project, "Hu" is the representation of the company name, and tool represents the tool. Hutool homonym "confused", on the one hand simple and easy to understand, on the other hand means "rare confused".

How Hutool changes the way we coding

The goal of Hutool is to use a tool method instead of a complex piece of code, so as to minimize the problem of "copy and paste" code and revolutionize the way we write code.

Take calculating MD5 as an example:

[previous] Open search engine-> search "Java MD5 encryption"-> Open a blog-> copy and paste-> make it easier to use

[now] introduce Hutool-> SecureUtil.md5 ()

The existence of Hutool is to reduce the cost of code search and avoid bug caused by uneven code on the network.

Include components

A Java basic utility class that encapsulates JDK methods such as file, stream, encryption and decryption, transcoding, regularization, threading, XML, etc., to form various Util utility classes, and provides the following components:

The module introduces hutool-aopJDK dynamic proxy encapsulation, provides aspect support for hutool-bloomFilter Bloom filtering under non-IOC, provides some Hash algorithm Bloom filtering hutool-cache simple cache to implement hutool-core core, including Bean operation, date, various Util and other hutool-cron timing task modules, provides Crontab expression-like timing task hutool-crypto encryption and decryption module, provides symmetric, asymmetric and digest algorithm encapsulation hutool-dbJDBC encapsulated data operation Based on ActiveRecord idea hutool-dfa based on DFA model multi-keyword search hutool-extra expansion module, for third-party packaging (template engine, mail, Servlet, QR code, Emoji, FTP, word segmentation, etc.) hutool-http based on HttpUrlConnection Http client encapsulation hutool-log automatic identification log implementation of log facade hutool-script script execution package For example, Javascripthutool-setting more powerful Setting configuration file and Properties encapsulation hutool-system system parameter call encapsulation (JVM information, etc.) hutool-jsonJSON implementation hutool-captcha picture verification code implementation hutool-poi encapsulation for Excel and Word in POI hutool-socket Java-based NIO and AIO Socket encapsulation

Maven

Add the following to the dependencies of the project's pom.xml:

Cn.hutool hutool-all 5.5.2 pain points

In Java development, we have to face a variety of type conversion problems, especially the user parameters obtained from the command line, the Parameter obtained from HttpRequest, etc., these parameter types are various, how do we convert them? The common way is to first integrate into String, and then call the XXX.parseXXX method, but also to bear the risk of conversion failure, have to add a layer of try catch, this small process mix-up will look very ugly and bloated in business code.

Convert class

The Convert class can be said to be a utility method class that encapsulates conversions for common Java types to simplify type conversions. Most of the methods in the Convert class are toXXX, with an argument of Object, which enables you to convert any possible type to a specified type. The second parameter, defaultValue, is also supported to return a default value if the conversion fails.

Java common type conversion

1. Convert to a string:

Int a = 1 "String aStr = Convert.toStr (a); long [] b = {1, 2, 3, 4, 5}; / / bStr is:" [1, 2, 2, 3, 4, 5, 5] "String bStr = Convert.toStr (b)

two。 Convert to an array of the specified type:

String [] b = {"1", "2", "3", "4"}; / / the result is the Integer array Integer [] intArray = Convert.toIntArray (b); long [] c = {1, intArray2, 3, 4, 5}; / / the result is the Integer array Integer [] intArray2 = Convert.toIntArray (c)

3. Convert to a date object:

String a = "2017-05-06"; Date value = Convert.toDate (a)

4. Convert to collection

Object [] a = {"a", "you", "Hello", "1}; List list = Convert.convert (List.class, a); / / you can use List list = Convert.toList (a) as of 4.1.11; other type conversions

1. Standard type

Any type can be converted to a specified type through the Convert.convert (Class, Object) method. Many type conversions are predefined in Hutool, such as URI, URL, Calendar, and so on, all of which are based on the ConverterRegistry class. Through this class and the Converter interface, we can customize some type conversions. For detailed use, see the "Custom Type conversion" section.

two。 Generic type

Using the convert (TypeReference reference, Object value) method, you can type-convert nested generics by new a TypeReference object. For example, if we want to convert an object to a List type, the standard Class passed in will not meet the requirements, so we can do this:

Object [] a = {"a", "you", "Hello", "1}; List list = Convert.convert (new TypeReference () {}, a)

After instantiating through TypeReference, the generic type is established, and the object can be converted to the target type we want.

Hexadecimal (Hex)

In many cases of encryption and decryption, as well as Chinese string transmission (such as form submission), hexadecimal conversion, that is, Hex conversion, is used. For this reason, the HexUtil utility class is specially encapsulated in Hutool. Considering that hexadecimal conversion is also part of the transformation, the method is also placed in the Convert class for easy understanding and lookup, and it is also very easy to use:

Convert to hexadecimal (Hex) string

String a = "I am a cute little string"; / / result: "e68891e698afe4b880e4b8aae5b08fe5b08fe79a84e58fafe788b1e79a84e5ad97e7aca6e4b8b2" String hex = Convert.toHex (a, CharsetUtil.CHARSET_UTF_8)

Convert a hexadecimal (Hex) string to a normal string:

String hex = "e68891e698afe4b880e4b8aae5b08fe5b08fe79a84e58fafe788b1e79a84e5ad97e7aca6e4b8b2"; / / the result is: "I am a cute little string" String raw = Convert.hexStrToStr (hex, CharsetUtil.CHARSET_UTF_8); / / Note: after 4.1.11, hexStrToStr will be renamed hexToStrString raw = Convert.hexToStr (hex, CharsetUtil.CHARSET_UTF_8).

Because the string involves encoding, the encoding object must be passed in, and UTF-8 encoding is used here. The toHex method also supports passing byte [], and you can also use the hexToBytes method to convert hexadecimal to byte []

Unicode and string conversion

Similar to hexadecimal, the convert class can easily convert between strings and Unicode:

String a = "I am a cute little string"; / / the result is: "\\ u6211\\ u662f\\ u4e00\\ u4e2a\\ u5c0f\\ u5c0f\\ u7684\ u53ef\\ u7231\\ u7684\\ u5b57\\ u7b26\\ u4e32" String unicode = Convert.strToUnicode (a); / / the result is: "I am a cute little string" String raw = Convert.unicodeToStr (unicode); transcoding

When receiving forms, we are often plagued by Chinese garbled. In fact, most of the reasons are that we use incorrect encoding to decode the data. So the Convert.convertCharset method comes in handy, turning garbled into the correct encoding:

String a = "I am not garbled"; / / converted result to garbled String result = Convert.convertCharset (a, CharsetUtil.UTF_8, CharsetUtil.ISO_8859_1); String raw = Convert.convertCharset (result, CharsetUtil.ISO_8859_1, "UTF-8"); Assert.assertEquals (raw, a)

Note that after testing, there are some problems of Chinese conversion failure after UTF-8 encoding, decoding with GBK and then decoding with GBK, and decoding with UTF-8.

Time unit conversion

The Convert.convertTime method is mainly used to convert time units, such as a large millisecond. I want to get how many minutes this millisecond corresponds to:

Long a = 4535345 / result: 75long minutes = Convert.convertTime (a, TimeUnit.MILLISECONDS, TimeUnit.MINUTES); conversion of amount to case

In the face of financial needs, Convert.digitToChinese converts the amount of money into uppercase:

Double a = 67556.32 / the result is: "Lu Wanqian Wu Baiwu Luyuan two points" String digitUppercase = Convert.digitToChinese (a)

Note that the conversion to uppercase can only be accurate to points (two digits after the decimal point), and subsequent numbers will be ignored.

Conversion between original class and wrapper class

Sometimes, when we need to convert the wrapper class to and from the original class (such as Integer.class and int.class), we can:

/ / unwrapped Class wrapClass = Integer.class;// result is: int.classClass unWraped = Convert.unWrap (wrapClass); / / wrapped Class primitiveClass = long.class;// result is: Long.classClass wraped = Convert.wrap (primitiveClass); formatted as a string

Call the toString () method to return a string of the format yyyy-MM-dd HH:mm:ss, and call toString (String format) to return a string of the specified format.

DateTime dateTime = new DateTime ("2017-01-05 12:34:23", DatePattern.NORM_DATETIME_FORMAT); / / result: 2017-01-05 12:34:23String dateStr = dateTime.toString (); / / result: 2017/01/05LocalDateTime tool-LocalDateTimeUtil use

Date conversion

String dateStr = "2020-01-23T12:23:56"; DateTime dt = DateUtil.parse (dateStr); / / Date object converted to LocalDateTimeLocalDateTime of = LocalDateTimeUtil.of (dt); / / timestamp converted to LocalDateTimeof = LocalDateTimeUtil.ofUTC (dt.getTime ())

Date string parsing

/ / parse ISO time LocalDateTime localDateTime = LocalDateTimeUtil.parse ("2020-01-23T12:23:56"); / / parse custom format time localDateTime = LocalDateTimeUtil.parse ("2020-01-23", DatePattern.NORM_DATE_PATTERN)

Parsing also supports LocalDate:

LocalDate localDate = LocalDateTimeUtil.parseDate ("2020-01-23"); / / the parsing date time is LocalDate, and the time part discards localDate = LocalDateTimeUtil.parseDate ("2020-01-23T12:23:56", DateTimeFormatter.ISO_DATE_TIME)

Date formatting

LocalDateTime localDateTime = LocalDateTimeUtil.parse ("2020-01-23T12:23:56"); / "2020-01-23 12:23:56" String format = LocalDateTimeUtil.format (localDateTime, DatePattern.NORM_DATETIME_PATTERN)

Date offset

Final LocalDateTime localDateTime = LocalDateTimeUtil.parse ("2020-01-23T12:23:56"); / / add one day / / "2020-01-24T12:23:56" LocalDateTime offset = LocalDateTimeUtil.offset (localDateTime, 1, ChronoUnit.DAYS)

If the time is reduced, the second parameter of offset can pass a negative number:

/ / "2020-01-22T12:23:56" offset = LocalDateTimeUtil.offset (localDateTime,-1, ChronoUnit.DAYS)

Date offset

LocalDateTime start = LocalDateTimeUtil.parse ("2019-02-02T00:00:00"); LocalDateTime end = LocalDateTimeUtil.parse ("2020-02-02T00:00:00"); Duration between = LocalDateTimeUtil.between (start, end); / / 365between.toDays ()

The beginning and end of the day

LocalDateTime localDateTime = LocalDateTimeUtil.parse ("2020-01-23T12:23:56"); / / "2020-01-23T00:00" LocalDateTime beginOfDay = LocalDateTimeUtil.beginOfDay (localDateTime); / / "2020-01-23T23:59:59.999999999" LocalDateTime endOfDay = LocalDateTimeUtil.endOfDay (localDateTime); string tool-StrUtil

1.removePrefix and removeSuffix methods

These two are stripped of the prefix and suffix of the string, such as the extension of a file name.

String fileName = StrUtil.removeSuffix ("pretty_girl.jpg", ".jpg") / / fileName-> pretty_girl

And removePrefixIgnoreCase and removeSuffixIgnoreCase, which ignore case, are more practical.

2. Sub method

I have to mention this method. Some people say that if String has subString, why do you write it? I want to say that subString method will report an exception when it crosses the boundary, and you have to judge for yourself. I've added all kinds of situation judgments, and the position of index also supports negative numbers.-1 represents the last character (this idea comes from Python, and those who have studied Python should like it very much.) In addition, if you accidentally reverse the first position and the second position, it will be corrected automatically (for example, it is possible to intercept the part between the fourth and second characters) give a chestnut.

String str = "abcdefgh"; String strSub1 = StrUtil.sub (str, 2,3); / / strSub1-> cString strSub2 = StrUtil.sub (str, 2,-3); / / strSub2-> cdeString strSub3 = StrUtil.sub (str, 3,2); / / strSub2-> c

3.format method

String template = "{} love {}, just like a mouse loves rice"; String str = StrUtil.format (template, "I", "you"); / / str-> I love you, just like a mouse loves rice

Parameter I defined as the Object type, if another type can also be passed, the toString () method will be called automatically.

Digester

Take MD5 as an example:

Digester md5 = new Digester (DigestAlgorithm.MD5); / / 5393554e94bf0eb6436f240a4fd71282String digestHex = md5.digestHex (testStr)

Of course, as the most commonly used methods, MD5 and other methods are encapsulated as tool methods in DigestUtil, the above code can be further simplified to:

/ / 5393554e94bf0eb6436f240a4fd71282String md5Hex1 = DigestUtil.md5Hex (testStr); Hutool-http

The easiest way to use it is to quickly request a page with the HttpUtil utility class:

/ / GET request String content = HttpUtil.get (url)

It can be done with one line of code, and of course the Post request is very simple:

/ / POST request HashMap paramMap = new HashMap (); paramMap.put ("city", "Beijing"); String result1 = HttpUtil.post (url, paramMap)

For a Post request, you only need to predefine the form form items using Map.

At this point, I believe you have a deeper understanding of "what components the Hutool tool contains". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report