Hutool中那些經常使用的工具類和方法

SpringBoot實戰電商項目mall(20k+star)地址:github.com/macrozheng/…java

摘要

Hutool是一個Java工具包,它幫助咱們簡化每一行代碼,避免重複造輪子。若是你有須要用到某些工具方法的時候,不妨在Hutool裏面找找,可能就有。本文將對Hutool中的經常使用工具類和方法進行介紹。git

安裝

maven項目在pom.xml添加如下依賴便可:github

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>4.6.3</version>
</dependency>
複製代碼

經常使用工具類

Convert

類型轉換工具類,用於各類類型數據的轉換。api

//轉換爲字符串
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反射工具類,可用於反射獲取類的方法及建立對象。app

//獲取某個類的全部方法
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

數字處理工具類,可用於各類類型數字的加減乘除操做及判斷類型。maven

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中的工具類不少,能夠參考:www.hutool.cn/

項目源碼地址

github.com/macrozheng/…

公衆號

mall項目全套學習教程連載中,關注公衆號第一時間獲取。

公衆號圖片
相關文章
相關標籤/搜索