Today to recommend a very easy to use Java tool class library, enterprise common tool class, basic have, can avoid repeating the wheel and save a lot of development time, very good, worth everyone to understand the use.
Hutool homonym “confused”, meaning the pursuit of “everything is confused view, no loss, no gain” realm.
Hutool is a Java toolkit, and only a toolkit, that helps us simplify every line of code, eliminate every method, and make the Java language “sweet.” Hutool was originally a compilation of the “util” package in my project. Later, it gradually accumulated and added more non-business related functions. Besides, I learned the essence of other open source projects extensively, and finally formed a rich set of open source tools through my own sorting and modification.
1, the function
Util utility class a Java basic utility class that encapsulates JDK methods such as files, streams, encryption and decryption, transcoding, re, threads, and XML. Util utility classes provide the following components:
-
Hutool – AOP JDK dynamic proxy package, providing aspect support under non-IOC
-
Hutool-bloomfilter Provides Bloomed filtering based on Hash algorithms
-
Hutool – cache cache
-
Hutool-core, including Bean operations, dates, various utils, etc
-
Hutool -cron Scheduled task module, which provides scheduled tasks like Crontab expressions
-
Hutool – Crypto encryption and decryption module
-
Hutool -db JDBC encapsulated data operations based on ActiveRecord
-
Hutool – DFA Multi-keyword lookup based on DFA model
-
Hutool – Extra extension module for third party encapsulation (template engine, mail, etc.)
-
Hutool-http HTTP client encapsulation based on HttpUrlConnection
-
Hutool-log Automatically identifies the log facade of the log implementation
-
Hutool-script Scripts perform encapsulation, such as Javascript
-
Hutool-setting features more powerful setting profile and Properties package
-
Hutool-system System parameters call encapsulation (JVM information, etc.)
-
Hutool – json json
-
Hutool – CaptCHA image verification code implementation
2, installation,
The Maven project adds the following dependencies to pom.xml:
< the dependency > < groupId > cn. Hutool < / groupId > < artifactId > hutool -all < / artifactId > < version > 4.6.3 < / version > < / dependency >Copy the code
3. Simple tests
CronUtil (scheduled task)
CronUtil doesn’t need a framework like Quartz to do scheduled tasks. CronUtil doesn’t need any dependencies, just create a configuration file under Resources and enable scheduled tasks when the application starts
cron.setting:
cc.ryanc.halo.web.controller.admin.BackupController.backupResources = 0 0 1 * * ? cc.ryanc.halo.web.controller.admin.BackupController.backupDatabase = 0 0 1 * * ? cc.ryanc.halo.web.controller.admin.BackupController.backupPosts = 0 0 1 * * ? @Overridepublic void onApplicationEvent(ContextRefreshedEvent event){ this.loadActiveTheme(); this.loadOptions(); this.loadFiles(); this.loadThemes(); // Start scheduled task cronutil.start (); Log.info (" Scheduled task started successfully!" ); }Copy the code
Convert
Type conversion utility class for converting various types of data.
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 code
DateUtil
The datetime utility class defines some common datetime manipulation methods.
Date = dateutil.date (); //Date = dateutil.date (); Datedate = dateutil.date (calendar.getInstance ()); Datedate = 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 code
StrUtil
The string utility class defines some common string manipulation methods.
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 code
ClassPathResource
Get files in the classPath, which is usually web-INF /classes in containers such as Tomcat.
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); ReflectUtilJava reflection utility class, which can be used to reflect the methods of getting classes and creating 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 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 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 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. Elegantly-named setName (" millet "); brand.setShowStatus(0); <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 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, ListHashMap<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 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 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 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 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(); }Copy the code
Hutool has a variety of tools available at www.hutool.cn/
Of course, there are many other very convenient methods, so leave them to your own test! Using Hutool, you can greatly improve your development efficiency!
PS: In case you can’t find this article, please click “like” to browse and find it