一、背景
在 GitHub 上見到過很多開源的自動化框架內都自帶了很多 Util 工具類,我們自己在開發自動化框架也必然需要用到工具類庫,那麼這樣就會帶來一些問題:
- API的學習成本
- 重複造輪子
- 封裝不完善帶來的bug
那麼,有沒有比較好的通用輪子讓我們直接使用呢?當然有,今天我們來介紹一下工具類庫—Hutool
二、Hutool 簡介
Hutool是一個小而全的Java工具類庫,通過靜態方法封裝,降低相關API的學習成本,提高工作效率,使Java擁有函數式語言般的優雅,讓Java語言也可以“甜甜的”。 Hutool中的工具方法來自於每個用戶的精雕細琢,它涵蓋了Java開發底層代碼中的方方面面,它既是大型項目開發中解決小問題的利器,也是小型項目中的效率擔當; Hutool是項目中“util”包友好的替代,它節省了開發人員對項目中公用類和公用工具方法的封裝時間,使開發專註於業務,同時可以最大限度的避免封裝不完善帶來的bug。
以上是摘自官網的介紹,如果我們有需要用到某些工具方法的時候,不妨在Hutool裡面找找。
官網地址:https://github.com/looly/hutool
三、Hutool 包含組件
一個Java基礎工具類,對文件、流、加密解密、轉碼、正則、線程、XML等JDK方法進行封裝,組成各種Util工具類,同時提供以下組件:

可以根據需求對每個模塊單獨引入,也可以通過引入hutool-all方式引入所有模塊。
四、安裝
1、Maven
在項目的pom.xml的dependencies中加入以下內容:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.2</version>
</dependency>2、Gradle
compile 'cn.hutool:hutool-all:5.4.2'3、非Maven項目
點擊以下任一鏈接,下載hutool-all-X.X.X.jar即可:
- Maven中央庫1
- Maven中央庫2
注意 Hutool 5.x支持 JDK8+,對 Android 平台沒有測試,不能保證所有工具類或工具方法可用。 如果你的項目使用 JDK7,請使用 Hutool 4.x 版本
五、常用工具類
1、Convert
類型轉換工具類,用於各種類型數據的轉換。
@Test(description = "Convert使用:類型轉換工具類")
public void covert() {
int a = 1;
String aStr = Convert.toStr(a);
//轉換為指定類型數組
String[] b = {"1", "2", "3", "4"};
Integer[] bArr = Convert.toIntArray(b);
log.info(bArr.toString());
//轉換為日期對象
String dateStr = "2020-09-17";
Date date = Convert.toDate(dateStr);
log.info(date.toString());
//轉換為列表
String[] strArr = {"a", "b", "c", "d"};
List<String> strList = Convert.toList(String.class, strArr);
log.info(strList.toString());
}
運行結果:
[Ljava.lang.Integer;@4c0884e8
Thu Sep 17 00:00:00 CST 2020
[a, b, c, d]2、DateUtil
日期時間工具類,定義了一些常用的日期時間操作方法。
@Test(description = "DateUtil使用:日期時間工具")
public void dateUtil() {
//Date、long、Calendar之間的相互轉換
//當前時間
Date date = DateUtil.date();
log.info(date.toString());
//Calendar轉Date
date = DateUtil.date(Calendar.getInstance());
//時間戳轉Date
date = DateUtil.date(System.currentTimeMillis());
//自動識別格式轉換
String dateStr = "2020-09-17";
date = DateUtil.parse(dateStr);
//自定義格式化轉換
date = DateUtil.parse(dateStr, "yyyy-MM-dd");
//格式化輸出日期
String format = DateUtil.format(date, "yyyy-MM-dd");
log.info(format.toString());
//獲得年的部分
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);
}運行結果:
2020-09-17 18:42:22
2020-09-173、StrUtil
字符串工具類,定義了一些常用的字符串操作方法。
@Test(description = "StrUtil使用:字符串工具")
public void 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, "我是佔位符");
log.info("/strUtil format:{}", str2);
}運行結果:
/strUtil format:這只是個佔位符:我是佔位符4、ClassPathResource
獲取 classPath 下的文件,在 Tomcat 等容器下,classPath一般是 WEB-INF/classes。
@Test(description = "ClassPath單一資源訪問類:在classPath下查找文件")
public void classPath() throws IOException {
//獲取定義在src/main/resources文件夾中的配置文件
ClassPathResource resource = new ClassPathResource("generator.properties");
Properties properties = new Properties();
properties.load(resource.getStream());
log.info("/classPath:{}", properties);
}運行結果:
/classPath:{jdbc.userId=root, jdbc.password=root, jdbc.driverClass=com.mysql.cj.jdbc.Driver, jdbc.connectionURL=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai}5、ReflectUtil
Java反射工具類,可用於反射獲取類的方法及創建對象。
@Test(description = "ReflectUtil使用:Java反射工具類")
public void reflectUtil() {
//獲取某個類的所有方法
Method[] methods = ReflectUtil.getMethods(Dog.class);
//獲取某個類的指定方法
Method method = ReflectUtil.getMethod(Dog.class, "getName");
//使用反射來創建對象
Dog dog = ReflectUtil.newInstance(Dog.class);
//反射執行對象的方法
ReflectUtil.invoke(dog, "setName","大黃");
log.info(dog.getName());
}Dog
Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Dog {
private String name;
private Float weight;
}運行結果:
大黃6、NumberUtil
數字處理工具類,可用於各種類型數字的加減乘除操作及判斷類型。
@Test(description = "NumberUtil使用:數字處理工具類")
public void 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);
}7、BeanUtil
JavaBean的工具類,可用於Map與JavaBean對象的互相轉換以及對象屬性的拷貝。
@Test(description = "BeanUtil使用:JavaBean的工具類")
public void beanUtil() {
Dog dog = new Dog();
dog.setName("大黃");
dog.setWeight(5.14f);
//Bean轉Map
Map<String, Object> map = BeanUtil.beanToMap(dog);
log.info("beanUtil bean to map:{}", map);
//Map轉Bean
Dog mapDog = BeanUtil.mapToBean(map, Dog.class, false);
log.info("beanUtil map to bean:{}", mapDog);
//Bean屬性拷貝
Dog copyDog = new Dog();
BeanUtil.copyProperties(dog, copyDog);
log.info("beanUtil copy properties:{}", copyDog);
}運行結果:
beanUtil bean to map:{name=大黃, weight=5.14}
beanUtil map to bean:Dog(name=大黃, weight=5.14)
beanUtil copy properties:Dog(name=大黃, weight=5.14)8、CollUtil
集合操作的工具類,定義了一些常用的集合操作。
@Test(description = "CollUtil使用:集合工具類")
public void collUtil() {
//數組轉換為列表
String[] array = new String[]{"a", "b", "c", "d", "e"};
List<String> list = CollUtil.newArrayList(array);
//join:數組轉字符串時添加連接符號
String joinStr = CollUtil.join(list, ",");
log.info("collUtil join:{}", joinStr);
//將以連接符號分隔的字符串再轉換為列表
List<String> splitList = StrUtil.split(joinStr, ',');
log.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);
CollUtil.isNotEmpty(list);
}運行結果:
collUtil join:a,b,c,d,e
collUtil split:[a, b, c, d, e]
9、MapUtil
Map操作工具類,可用於創建 Map 對象及判斷 Map 是否為空。
@Test(description = "MapUtil使用:Map工具類")
public void mapUtil() {
//將多個鍵值對加入到Map中
Map<Object, Object> map = MapUtil.of(new String[][]{
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}
});
//判斷Map是否為空
MapUtil.isEmpty(map);
MapUtil.isNotEmpty(map);
}10、SecureUtil
加密解密工具類,可用於 MD5 加密。
@Test(description = "SecureUtil使用:加密解密工具類")
public void secureUtil() {
//MD5加密
String str = "123456";
String md5Str = SecureUtil.md5(str);
log.info("secureUtil md5:{}", md5Str);
}
運行結果:
secureUtil md5:e10adc3949ba59abbe56e057f20f883e11、CaptchaUtil
驗證碼工具類,可用於生成圖形驗證碼。
@Test(description = "CaptchaUtil使用:圖形驗證碼")
public void captchaUtil(HttpServletRequest request, HttpServletResponse response) {
//生成驗證碼圖片
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();
}
}12、Validator
字段驗證器,驗證給定字符串是否滿足指定條件,一般用在表單字段驗證里。
@Test(description = "Validator使用:字段驗證器")
public void validator() {
//判斷是否為郵箱地址
boolean result = Validator.isEmail("zuozewei@hotmail.com");
log.info("Validator isEmail:{}", result);
//判斷是否為手機號碼
result = Validator.isMobile("18911111111");
log.info("Validator isMobile:{}", result);
//判斷是否為IPV4地址
result = Validator.isIpv4("192.168.3.101");
log.info("Validator isIpv4:{}", result);
//判斷是否為漢字
result = Validator.isChinese("你好");
log.info("Validator isChinese:{}", result);
//判斷是否為身份證號碼(18位中國)
result = Validator.isCitizenId("123456");
log.info("Validator isCitizenId:{}", result);
//判斷是否為URL
result = Validator.isUrl("http://www.7d.com");
log.info("Validator isUrl:{}", result);
//判斷是否為生日
result = Validator.isBirthday("2020-09-17");
log.info("Validator isBirthday:{}", result);
}運行結果:
Validator isEmail:true
Validator isMobile:true
Validator isIpv4:true
Validator isChinese:true
Validator isCitizenId:false
Validator isUrl:true
Validator isBirthday:true13、JSONUtil
JSON 解析工具類,針對 JSONObject 和 JSONArray 的靜態快捷方法集合。
@Test(description = "JSONUtil使用:JSON解析工具類")
public void jsonUtil() {
Dog dog = new Dog();
dog.setName("大黃");
dog.setWeight(5.14f);
//對象轉化為JSON字符串
String jsonStr = JSONUtil.parse(dog).toString();
log.info("jsonUtil parse:{}", jsonStr);
//JSON字符串轉化為對象
Dog dogBean = JSONUtil.toBean(jsonStr, Dog.class);
log.info("jsonUtil toBean:{}", dogBean);
List<Dog> dogList = new ArrayList<>();
dogList.add(dog);
String jsonListStr = JSONUtil.parse(dogList).toString();
//JSON字符串轉化為列表
dogList = JSONUtil.toList(new JSONArray(jsonListStr), Dog.class);
log.info("jsonUtil toList:{}", dogList);
}
運行結果:
jsonUtil parse:{"weight":5.14,"name":"大黃"}
jsonUtil toBean:Dog(name=大黃, weight=5.14)
jsonUtil toList:[Dog(name=大黃, weight=5.14)]14、RandomUtil
隨機工具類,RandomUtil 主要針對 JDK 中 Random 對象做封裝。
@Test(description = "RandomUtil使用:隨機工具類")
public void randomUtil() {
int result;
String uuid;
//獲得指定範圍內的隨機數
result = RandomUtil.randomInt(1, 100);
log.info("randomInt:{}",StrUtil.toString(result));
//獲得隨機UUID
uuid = RandomUtil.randomUUID();
log.info("randomUUID:{}", uuid);
}運行結果:
randomInt:9
randomUUID:8aec5890-72ab-4d72-a37d-d36acba83b5815、DigestUtil
摘要算法工具類,支持常見摘要算法 MD2、MD5、SHA-1、SHA-256、SHA-384、SHA-512等。
@Test(description = "DigestUtil使用:摘要算法工具類")
public void digestUtil() {
String password = "123456";
//計算MD5摘要值,並轉為16進制字符串
String result = DigestUtil.md5Hex(password);
log.info("DigestUtil md5Hex:{}", result);
//計算SHA-256摘要值,並轉為16進制字符串
result = DigestUtil.sha256Hex(password);
log.info("DigestUtil sha256Hex:{}", result);
//生成Bcrypt加密後的密文,並校驗
String hashPwd = DigestUtil.bcrypt(password);
boolean check = DigestUtil.bcryptCheck(password,hashPwd);
log.info("DigestUtil bcryptCheck:{}", check);
}
運行結果:
DigestUtil md5Hex:e10adc3949ba59abbe56e057f20f883e
DigestUtil sha256Hex:8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
DigestUtil bcryptCheck:true16、HttpUtil
Http客戶端工具類,應對簡單場景下Http請求的工具類封裝,此工具封裝了HttpRequest對象常用操作,可以保證在一個方法之內完成Http請求。
此模塊基於JDK的HttpUrlConnection封裝完成,完整支持https、代理和文件上傳。
@Test(description = "HttpUtil使用:Http請求工具類")
public void httpUtil() {
String response = HttpUtil.get("http://example.com/");
log.info("HttpUtil get:{}", response);
}運行結果:
2020-09-17 18:48:27.328 INFO 12004 --- [ main] com.zuozewei.demo.example.example : HttpUtil get:<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
body {
background-color: #f0f0f2;
margin: 0;
padding: 0;
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
div {
width: 600px;
margin: 5em auto;
padding: 2em;
background-color: #fdfdff;
border-radius: 0.5em;
box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
}
a:link, a:visited {
color: #38488f;
text-decoration: none;
}
@media (max-width: 700px) {
div {
margin: 0 auto;
width: auto;
}
}
</style>
</head>
<body>
<div>
<h1>Example Domain</h1>
<p>This domain is for use in illustrative examples in documents. You may use this
domain in literature without prior coordination or asking for permission.</p>
<p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>17、其他工具類
Hutool中的工具類很多
六、小結
測試開發過程中要善於半開源,半代碼的方式,節省開發時間,合理利用輪子,提高工作效率。
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/222689.html
微信掃一掃
支付寶掃一掃