Hutool中那些常用的工具类和方法

Posted 普通网友

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hutool中那些常用的工具类和方法相关的知识,希望对你有一定的参考价值。

今天给大家分享一个在我们Java后端日常开发中经常会用到的一个工具-Hutool,下面是快速使用教程,欢迎大家的留言和讨论。

Hutool是一个Java工具包,它帮助我们简化每一行代码,避免重复造轮子。如果你有需要用到某些工具方法的时候,不妨在Hutool里面找找,可能就有。本文将对Hutool中的常用工具类和方法进行介绍。

安装

maven项目在pom.xml添加以下依赖即可:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>4.6.3</version>
</dependency>

Convert

类型转换工具类,用于各种类型数据的转换。

//转换为字符串
int a = 1;
String aStr = Convert.toStr(a);
//转换为指定类型数组
String[] b = "1", "2", "3", "4";
Integer[] bArr = Convert.toIntArray(b);
//转换为日期对象
String dateStr = "2017-05-06";
Date date = Convert.toDate(dateStr);
//转换为列表
String[] strArr = "a", "b", "c", "d";
List<String> strList = Convert.toList(String.class, strArr);

DateUtil

日期时间工具类,定义了一些常用的日期时间操作方法。

//Date、long、Calendar之间的相互转换
//当前时间
Date date = DateUtil.date();
//Calendar转Date
date = DateUtil.date(Calendar.getInstance());
//时间戳转Date
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);
//获得月份,从0开始计数
int month = DateUtil.month(date);
//获取某天的开始、结束时间
Date beginOfDay = DateUtil.beginOfDay(date);
Date endOfDay = DateUtil.endOfDay(date);
//计算偏移后的日期时间
Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
//计算日期时间之间的偏移量
long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY);

StrUtil

字符串工具类,定义了一些常用的字符串操作方法。

//判断是否为空字符串
String str = "test";
StrUtil.isEmpty(str);
StrUtil.isNotEmpty(str);
//去除字符串的前后缀
StrUtil.removeSuffix("a.jpg", ".jpg");
StrUtil.removePrefix("a.jpg", "a.");
//格式化字符串
String template = "这只是个占位符:";
String str2 = StrUtil.format(template, "我是占位符");
LOGGER.info("/strUtil format:", str2);

ClassPathResource

获取classPath下的文件,在Tomcat等容器下,classPath一般是WEB-INF/classes。

//获取定义在src/main/resources文件夹中的配置文件
ClassPathResource resource = new ClassPathResource("generator.properties");
Properties properties = new Properties();
properties.load(resource.getStream());
LOGGER.info("/classPath:", properties);

ReflectUtil

Java反射工具类,可用于反射获取类的方法及创建对象。

//获取某个类的所有方法
Method[] methods = ReflectUtil.getMethods(PmsBrand.class);
//获取某个类的指定方法
Method method = ReflectUtil.getMethod(PmsBrand.class, "getId");
//使用反射来创建对象
PmsBrand pmsBrand = ReflectUtil.newInstance(PmsBrand.class);
//反射执行对象的方法
ReflectUtil.invoke(pmsBrand, "setId", 1);

NumberUtil

数字处理工具类,可用于各种类型数字的加减乘除操作及判断类型。

double n1 = 1.234;
double n2 = 1.234;
double result;
//对float、double、BigDecimal做加减乘除操作
result = NumberUtil.add(n1, n2);
result = NumberUtil.sub(n1, n2);
result = NumberUtil.mul(n1, n2);
result = NumberUtil.div(n1, n2);
//保留两位小数
BigDecimal roundNum = NumberUtil.round(n1, 2);
String n3 = "1.234";
//判断是否为数字、整数、浮点数
NumberUtil.isNumber(n3);
NumberUtil.isInteger(n3);
NumberUtil.isDouble(n3);

BeanUtil

JavaBean的工具类,可用于Map与JavaBean对象的互相转换以及对象属性的拷贝。

PmsBrand brand = new PmsBrand();
brand.setId(1L);
brand.setName("小米");
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);
//Bean属性拷贝
PmsBrand copyBrand = new PmsBrand();
BeanUtil.copyProperties(brand, copyBrand);
LOGGER.info("beanUtil copy properties:", copyBrand);

CollUtil

集合操作的工具类,定义了一些常用的集合操作。

//数组转换为列表
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);
//创建新的Map、Set、List
HashMap<Object, Object> newMap = CollUtil.newHashMap();
HashSet<Object> newHashSet = CollUtil.newHashSet();
ArrayList<Object> newList = CollUtil.newArrayList();
//判断列表是否为空
CollUtil.isEmpty(list);

MapUtil

Map操作工具类,可用于创建Map对象及判断Map是否为空。

//将多个键值对加入到Map中
Map<Object, Object> map = MapUtil.of(new String[][]
    "key1", "value1",
    "key2", "value2",
    "key3", "value3"
);
//判断Map是否为空
MapUtil.isEmpty(map);
MapUtil.isNotEmpty(map);

AnnotationUtil

注解工具类,可用于获取注解与注解中指定的值。

//获取指定类、方法、字段、构造器上的注解列表
Annotation[] annotationList = AnnotationUtil.getAnnotations(HutoolController.class, false);
LOGGER.info("annotationUtil annotations:", annotationList);
//获取指定类型注解
Api api = AnnotationUtil.getAnnotation(HutoolController.class, Api.class);
LOGGER.info("annotationUtil api value:", api.description());
//获取指定类型注解的值
Object annotationValue = AnnotationUtil.getAnnotationValue(HutoolController.class, RequestMapping.class);

SecureUtil

加密解密工具类,可用于MD5加密。

//MD5加密
String str = "123456";
String md5Str = SecureUtil.md5(str);
LOGGER.info("secureUtil md5:", md5Str);

CaptchaUtil

验证码工具类,可用于生成图形验证码。

//生成验证码图片
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
try 
    request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
    response.setContentType("image/png");//告诉浏览器输出内容为图片
    response.setHeader("Pragma", "No-cache");//禁止浏览器缓存
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expire", 0);
    lineCaptcha.write(response.getOutputStream());
 catch (IOException e) 
    e.printStackTrace();


Hutool中的工具类很多,可以参考官网:https://www.hutool.cn/
# 最后

关于面试刷题也是有方法可言的,建议最好是按照专题来进行,然后由基础到高级,由浅入深来,效果会更好。当然,这些内容我也全部整理在一份pdf文档内,分成了以下几大专题:

*   Java基础部分

![](https://img-blog.csdnimg.cn/img_convert/8df57e798c781582b717c752c21e9f2a.png)

*   算法与编程

![](https://img-blog.csdnimg.cn/img_convert/ebaec4a6d74d7e4182cf58c052e0d79f.png)

*   数据库部分

![](https://img-blog.csdnimg.cn/img_convert/0b77c5858220bd8fa277a19e1eb65cef.png)

*   流行的框架与新技术(Spring+SpringCloud+SpringCloudAlibaba![](https://img-blog.csdnimg.cn/img_convert/3f0e26ea8f3b3ba00d75acb1de08376a.png)

这份面试文档当然不止这些内容,实际上像JVM、设计模式、ZK、MQ、数据结构等其他部分的面试内容均有涉及,因为文章篇幅,就不全部在这里阐述了。

**作为一名程序员,阶段性的学习是必不可少的,而且需要保持一定的持续性,这次在这个阶段内,我对一些重点的知识点进行了系统的复习,一方面巩固了自己的基础,另一方面也提升了自己的知识广度和深度。**

最后提醒一下哦,如果你想要学习,却无奈于没有干货学习资料,以上所有的资料内容都可以免费分享给你,只需你多多支持一下即可

iMcKVp3B-1623561314595)]

这份面试文档当然不止这些内容,实际上像JVM、设计模式、ZK、MQ、数据结构等其他部分的面试内容均有涉及,因为文章篇幅,就不全部在这里阐述了。

**作为一名程序员,阶段性的学习是必不可少的,而且需要保持一定的持续性,这次在这个阶段内,我对一些重点的知识点进行了系统的复习,一方面巩固了自己的基础,另一方面也提升了自己的知识广度和深度。**

最后提醒一下哦,如果你想要学习,却无奈于没有干货学习资料,以上所有的资料内容都可以免费分享给你,只需你多多支持一下即可

**[“点赞文章,关注我,然后戳戳戳戳这里获取免费下载方式”](https://docs.qq.com/doc/DSmxTbFJ1cmN1R2dB)**

以上是关于Hutool中那些常用的工具类和方法的主要内容,如果未能解决你的问题,请参考以下文章

huTool--工具类常用方法

hutool工具类判断是不是包含中文

7hutool实战:FileUtil 文件工具类(100多个文件常用操作方法)

7hutool实战:FileUtil 文件工具类(100多个文件常用操作方法)

7hutool实战FileUtil 文件工具类(100多个文件常用操作方法)

Hutool常用工具类