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/

 

文章來源:https://macrozheng.github.io/mall-learning/#/reference/hutool


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM