Hutool是一个小而全的Java工具类库,它帮忙咱们简化每一行代码,防止反复造轮子。如果你有须要用到某些工具类的时候,无妨在Hutool外面找找。本文总结了平时罕用的16个工具类,心愿对大家有所帮忙!

SpringBoot实战电商我的项目mall(40k+star)地址:https://github.com/macrozheng/mall

装置

Hutool的装置非常简单,Maven我的项目中只需在pom.xml增加以下依赖即可。

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

常用工具类

应用一个工具办法代替一段简单代码,防止复制粘贴代码,能够极大的进步咱们的开发效率,上面介绍下我罕用的工具办法!

Convert

类型转换工具类,用于各种类型数据的转换。平时咱们转换类型常常会面临类型转换失败的问题,要写try catch代码,有了它,就不必写了!

//转换为字符串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

日期工夫工具类,定义了一些罕用的日期工夫操作方法。JDK自带的Date和Calendar对象真心不好用,有了它操作日期工夫就简略多了!

//Date、long、Calendar之间的互相转换//以后工夫Date date = DateUtil.date();//Calendar转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);//取得月份,从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);

JSONUtil

JSON解析工具类,可用于对象与JSON之间的互相转化。

PmsBrand brand = new PmsBrand();brand.setId(1L);brand.setName("小米");brand.setShowStatus(1);//对象转化为JSON字符串String jsonStr = JSONUtil.parse(brand).toString();LOGGER.info("jsonUtil parse:{}", jsonStr);//JSON字符串转化为对象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();//JSON字符串转化为列表brandList = JSONUtil.toList(new JSONArray(jsonListStr), PmsBrand.class);LOGGER.info("jsonUtil toList:{}", brandList);

StrUtil

字符串工具类,定义了一些罕用的字符串操作方法。StrUtilStringUtil名称更短,用起来也更不便!

//判断是否为空字符串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繁多资源拜访类,能够获取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转MapMap<String, Object> map = BeanUtil.beanToMap(brand);LOGGER.info("beanUtil bean to map:{}", map);//Map转BeanPmsBrand 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、ListHashMap<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();}

Validator

字段验证器,能够对不同格局的字符串进行验证,比方邮箱、手机号、IP等格局。

//判断是否为邮箱地址boolean result = Validator.isEmail("macro@qq.com");LOGGER.info("Validator isEmail:{}", result);//判断是否为手机号码result = Validator.isMobile("18911111111");LOGGER.info("Validator isMobile:{}", result);//判断是否为IPV4地址result = Validator.isIpv4("192.168.3.101");LOGGER.info("Validator isIpv4:{}", result);//判断是否为汉字result = Validator.isChinese("你好");LOGGER.info("Validator isChinese:{}", result);//判断是否为身份证号码(18位中国)result = Validator.isCitizenId("123456");LOGGER.info("Validator isCitizenId:{}", result);//判断是否为URLresult = Validator.isUrl("http://www.baidu.com");LOGGER.info("Validator isUrl:{}", result);//判断是否为生日result = Validator.isBirthday("2020-02-01");LOGGER.info("Validator isBirthday:{}", result);

DigestUtil

摘要算法工具类,反对MD5、SHA-256、Bcrypt等算法。

String password = "123456";//计算MD5摘要值,并转为16进制字符串String result = DigestUtil.md5Hex(password);LOGGER.info("DigestUtil md5Hex:{}", result);//计算SHA-256摘要值,并转为16进制字符串result = DigestUtil.sha256Hex(password);LOGGER.info("DigestUtil sha256Hex:{}", result);//生成Bcrypt加密后的密文,并校验String hashPwd = DigestUtil.bcrypt(password);boolean check = DigestUtil.bcryptCheck(password,hashPwd);LOGGER.info("DigestUtil bcryptCheck:{}", check);

HttpUtil

Http申请工具类,能够发动GET/POST等申请。

String response = HttpUtil.get("http://localhost:8080/hutool/covert");LOGGER.info("HttpUtil get:{}", response);

其余工具类

Hutool中的工具类还有很多,能够参考:https://www.hutool.cn/

我的项目源码地址

https://github.com/macrozheng...

本文 GitHub https://github.com/macrozheng/mall-learning 曾经收录,欢送大家Star!