Hutool—让Java也可以甜甜的
简单介绍
Hutool是Hu + tool的自造词,前者致敬我的“前任公司”,后者为工具之意,谐音“糊涂”,寓意追求“万事都作糊涂观,无所谓失,无所谓得”的境界。
Hutool是一个Java工具包,也只是一个工具包,它帮助我们简化每一行代码,减少每一个方法,让Java语言也可以“甜甜的”。Hutool最初是我项目中“util”包的一个整理,后来慢慢积累并加入更多非业务相关功能,并广泛学习其它开源项目精髓,经过自己整理修改,最终形成丰富的开源工具集。
本文介绍一下Hutool平时常用的16个工具类
使用
Hutool使用起来其实很简单,只需要在Maven中引入相关的依赖就可以进行使用了
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.2</version>
</dependency>
常用工具类
Convert
类型转换工具类,用于各种类型数据的转换。平时我们转换类型经常会面临类型转换失败的问题,要写try catch
代码,有了它,就不用写了!
/*
int类型转为String类型
*/
int a=1;
String s = Convert.toStr(a);
/**
* String数组转为Integer数组
*/
String[] b={"1","2","4","5"};
Integer[] integers = Convert.toIntArray(b);
/**
* 转为时间Date格式
*/
String dateStr="2020-09-10";
Date date = Convert.toDate(dateStr);
System.out.println(date);
/**
* 转为集合对象
*/
String[] strArr={"a","b","c","d"};
List<String> strings = Convert.toList(String.class, strArr);
DateUitl
日期时间工具类,定义了一些常用的日期时间操作方法。JDK自带的Date和Calendar对象真心不好用,有了它操作日期时间就简单多了!
/**
* Date转换 当前时间
*/
Date date = DateUtil.date();
System.out.println(date);
/**
* Calendar转Date
*/
Date time = DateUtil.date(Calendar.getInstance());
System.out.println(time);
/**
* 时间戳转Date
*/
Date date1 = DateUtil.date(System.currentTimeMillis());
System.out.println(date1);
/**
* 自定识别格式转换
*/
String dateStr="2020-09-11";
System.out.println(DateUtil.parse(dateStr));
/**
* 自定义格式转换
*/
System.out.println(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);
/**
* 获得某天开始和结束的时间
*/
DateTime beginOfDay = DateUtil.beginOfDay(date);
DateTime endOfDay = DateUtil.endOfDay(date);
/**
* 计算偏移后的日期时间
*/
DateTime newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
/**
* 计算时间之间的偏移量
*/
long between = DateUtil.between(date, newDate, DateUnit.DAY);
JSONUtil
JSON解析工具类,可用于对象与JSON之间的互相转化。
PmsBrand brand = new PmsBrand();
brand.setId(1L);
brand.setName("小楠");
brand.setShowStatus(1);
//将对象转为Json字符串
String jsonStr= JSONUtil.parse(brand).toString();
System.out.println(jsonStr);
//Json字符串转为对象
PmsBrand pmsBrand = JSONUtil.toBean(jsonStr, PmsBrand.class);
System.out.println(pmsBrand);
List<PmsBrand> brandList = new ArrayList<PmsBrand>();
brandList.add(brand);
//集合转为Json字符串
String jsonListStr = JSONUtil.parse(brandList).toString();
//json字符串转为集合对象
List<PmsBrand> pmsBrandList = JSONUtil.toList(new JSONArray(jsonListStr), PmsBrand.class);
StrUtil
字符串工具类,定义了一些常用的字符串操作方法。StrUtil
比StringUtil
名称更短,用起来也更方便!
String str ="StrUtil";
/**
* 判断字符串是否为空
*/
boolean empty = StrUtil.isEmpty(str);
boolean notEmpty = StrUtil.isNotEmpty(str);
/**
* 去除字符串的前缀和后缀
*/
String prefix = StrUtil.removePrefix("look.png", ".png");
String suffix = StrUtil.removeSuffix("look.png", "look.");
/**
* 格式化字符串
*/
String template="占位符:{}";
String format = StrUtil.format(template, "占位成功");
System.out.println(format);
HttpUtil
Http请求工具类,可以发起GET/POST等请求。
/**
* 可以发起GET/POST请求
*/
String response = HttpUtil.get("192.168.31.1:8888/hutool/covert");
DigestUtil
摘要算法工具类,支持MD5、SHA-256、Bcrypt等算法。
String password="1234567";
//计算MD5摘要值,并转为16进制字符串
String md5Hex = DigestUtil.md5Hex(password);
System.out.println(md5Hex);
//计算SHA-256摘要值,并转为16进制字符串
String sha256Hex = DigestUtil.sha256Hex(password);
System.out.println(sha256Hex);
//生成Bcrypt加密后的密文,并进行校验
String hashPwd = DigestUtil.bcrypt(password);
System.out.println(hashPwd);
boolean check = DigestUtil.bcryptCheck(password, hashPwd);
System.out.println(check);
Validator
字段验证器,可以对不同格式的字符串进行验证,比如邮箱、手机号、IP等格式。
//判断是否为邮箱地址
boolean email = Validator.isEmail("code@");
//判断是否为手机号码
boolean mobile = Validator.isMobile("19764565421");
//判断是否为ipv4的地址
boolean ipv4 = Validator.isIpv4("192.168.31.1");
//判断是否为汉字
boolean chinese = Validator.isChinese("小楠");
//判断是否为身份证号码
boolean citizenId = Validator.isCitizenId("12456645");
//判断是否为URL
boolean url = Validator.isUrl("http://www.codeyaco.cn");
//判断是否为生日
boolean birthday = Validator.isBirthday("2020-10-09");
CaptchaUtil
验证码工具类,可以用来生成图形验证码
CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(200, 100);
try {
request.getSession().setAttribute("CAPTCHA_KEY", circleCaptcha.getCode());
//告诉浏览器输出内容为图片
response.setContentType("image/png");
//禁止浏览器缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expire", 0);
circleCaptcha.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
SecureUtil
加密解密工具类,可用于MD5加密。
String str="123456789";
String md5 = SecureUtil.md5(str);
System.out.println(md5);
ClassPathResource
ClassPath单一资源访问类,可以获取classPath下的文件,在Tomcat等容器下,classPath一般是WEB-INF/classes。
ClassPathResource classPathResource = new ClassPathResource("generator.properties");
Properties properties = new Properties();
try {
properties.load(classPathResource.getStream());
} catch (IOException e) {
e.printStackTrace();
} catch (NoResourceException e) {
e.printStackTrace();
}
ReflectUtil
Java反射工具类,可用于反射获取类的方法及创建对象。
/**
* 获取某个类的所有方法
*/
Method[] method = ReflectUtil.getMethods(PmsBrand.class);
/**
* 获取某个类的指定方法
*/
Method getId = ReflectUtil.getMethod(PmsBrand.class, "getId");
/**
* 实用反射来创建对象
*/
PmsBrand pmsBrand = ReflectUtil.newInstance(PmsBrand.class);
/**
* 反射执行对象的方法
*/
ReflectUtil.invoke(pmsBrand,"setId",1);
NumberUtil
数字处理工具类,可用于各种类型数字的加减乘除操作及类型判断。
double num1 = 1.234;
double num2 = 1.234;
double result;
/**
* 对float,double,BigDecimal做加减乘除
*/
result = NumberUtil.add(num1, num2);
result = NumberUtil.sub(num1, num2);
result = NumberUtil.mul(num1, num2);
result = NumberUtil.div(num1, num2);
/**
* 保留两位小数
*/
BigDecimal bigDecimal = NumberUtil.round(num1, 2);
/**
* 判断是否为数字、整数、浮点数
*/
String str="1.234";
boolean number = NumberUtil.isNumber(str);
boolean integer = NumberUtil.isInteger(str);
boolean aDouble = NumberUtil.isDouble(str);
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);
/**
* Map转Bean
*/
PmsBrand pmsBrand = BeanUtil.mapToBean(map, PmsBrand.class, false);
/**
* Bean属性拷贝
*/
PmsBrand copyPmsBrand = new PmsBrand();
BeanUtil.copyProperties(brand,copyPmsBrand);
CollUtil
集合操作的工具类,定义了一些常用的集合操作。
/**
* 数组转为集合
*/
String[] array = {"a", "b", "c", "d", "e"};
ArrayList<String> newArrayList = CollUtil.newArrayList(array);
/**
* join:数组转字符串时添加连接符号
*/
String join = CollUtil.join(newArrayList, ",");
/**
* 将以连接符号分隔的字符串再转换为列表
*/
String[] split = StrUtil.split(join, ",");
ArrayList<String> strings = CollUtil.newArrayList(split);
/**
* 创建新的 Map Set List
*/
HashMap<Object, Object> hashMap = CollUtil.newHashMap();
HashSet<Object> set = CollUtil.newHashSet();
ArrayList<Object> arrayList = CollUtil.newArrayList();
/**
* 判断集合是否为空
*/
boolean empty = CollUtil.isEmpty(newArrayList);
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[] annotations = AnnotationUtil.getAnnotations(HuToolController.class, false);
/**
* 获取指定类型注解
*/
Reference annotation = AnnotationUtil.getAnnotation(HuToolController.class, Reference.class);
/**
* 获取指定注解的值
*/
Object annotationValue = AnnotationUtil.getAnnotationValue(HuToolController.class, Reference.class);