來源:公眾號 作者:Java知音
鏈接:https://mp.weixin.qq.com/s/0MwV0ZnuZv8qAJzHlUXSLA
前言
在java的龐大體系中贬养,其實有很多不錯的小工具闺金,也就是我們平常說的:輪子
乞巧。
如果在我們的日常工作當(dāng)中沙合,能夠?qū)⑦@些輪子用戶桩卵,再配合一下idea的快捷鍵降盹,可以極大得提升我們的開發(fā)效率。
今天我決定把一些壓箱底的小工具,分享給大家忌锯,希望對你有所幫助。
本文會分享17個我們?nèi)粘9ぷ髦幸欢〞玫玫降男」ぞ吡祆牛饕獌?nèi)容如下:
1. Collections
首先出場的是java.util
包下的Collections
類偶垮,該類主要用于操作集合或者返回集合,我個人非常喜歡用它帝洪。
1.1 排序
在工作中經(jīng)常有對集合排序的需求似舵。
看看使用Collections
工具是如何實現(xiàn)升序和降序的:
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
Collections.sort(list);//升序
System.out.println(list);
Collections.reverse(list);//降序
System.out.println(list);
執(zhí)行結(jié)果:
[1, 2, 3]
[3, 2, 1]
1.2 獲取最大或最小值
有時候需要找出集合中的最大值
或者最小值
,這時可以使用Collections的max
和min
方法碟狞。例如:
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
Integer max = Collections.max(list);//獲取最大值
Integer min = Collections.min(list);//獲取最小值
System.out.println(max);
System.out.println(min);
執(zhí)行結(jié)果:
3
1
1.3 轉(zhuǎn)換線程安全集合
我們都知道啄枕,java中的很多集合,比如:ArrayList族沃、LinkedList频祝、HashMap泌参、HashSet等,都是線程不安全的常空。
換句話說沽一,這些集合在多線程的環(huán)境中,添加數(shù)據(jù)會出現(xiàn)異常漓糙。
這時铣缠,可以用Collections的synchronizedxxx
方法,將這些線程不安全的集合昆禽,直接轉(zhuǎn)換成線程安全集合蝗蛙。例如:
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
List<Integer> integers = Collections.synchronizedList(list);//將ArrayList轉(zhuǎn)換成線程安全集合
System.out.println(integers);
它的底層會創(chuàng)建SynchronizedRandomAccessList
或者SynchronizedList
類,這兩個類的很多方法都會用synchronized
加鎖醉鳖。
1.4 返回空集合
有時捡硅,我們在判空之后,需要返回空集合盗棵,就可以使用emptyList
方法壮韭,例如:
private List<Integer> fun(List<Integer> list) {
if (list == null || list.size() == 0) {
return Collections.emptyList();
}
//業(yè)務(wù)處理
return list;
}
1.5 二分查找
binarySearch
方法提供了一個非常好用的二分查找
功能,只用傳入指定集合和需要找到的key即可纹因。例如:
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
int i = Collections.binarySearch(list, 3);//二分查找
System.out.println(i );
執(zhí)行結(jié)果:
2
1.6 轉(zhuǎn)換成不可修改集合
為了防止后續(xù)的程序把某個集合的結(jié)果修改了喷屋,有時候我們需要把某個集合定義成不可修改的,使用Collections的unmodifiablexxx
方法就能輕松實現(xiàn):
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
List<Integer> integers = Collections.unmodifiableList(list);
integers.add(4);
System.out.println(integers);
執(zhí)行結(jié)果:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
at com.sue.jump.service.test1.UtilTest.main(UtilTest.java:19)
當(dāng)然Collections工具類中還有很多常用的方法瞭恰,在這里就不一一介紹了屯曹,需要你自己去探索。
2. CollectionUtils
對集合操作寄疏,除了前面說的Collections
工具類之后是牢,CollectionUtils
工具類也非常常用僵井。
目前比較主流的是spring
的org.springframework.util
包下的CollectionUtils工具類陕截。
和apache
的org.apache.commons.collections
包下的CollectionUtils工具類。
我個人更推薦使用apache的包下的CollectionUtils工具類批什,因為它的工具更多更全面农曲。
舉個簡單的例子,spring
的CollectionUtils工具類沒有判斷集合不為空的方法驻债。而apache
的CollectionUtils工具類卻有乳规。
下面我們以apache
的CollectionUtils工具類為例,介紹一下常用方法合呐。
2.1 集合判空
通過CollectionUtils工具類的isEmpty
方法可以輕松判斷集合是否為空暮的,isNotEmpty
方法判斷集合不為空。
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
if (CollectionUtils.isEmpty(list)) {
System.out.println("集合為空");
}
if (CollectionUtils.isNotEmpty(list)) {
System.out.println("集合不為空");
}
2.2 對兩個集合進行操作
有時候我們需要對已有的兩個集合進行操作淌实,比如取交集或者并集等冻辩。
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
List<Integer> list2 = new ArrayList<>();
list2.add(2);
list2.add(4);
//獲取并集
Collection<Integer> unionList = CollectionUtils.union(list, list2);
System.out.println(unionList);
//獲取交集
Collection<Integer> intersectionList = CollectionUtils.intersection(list, list2);
System.out.println(intersectionList);
//獲取交集的補集
Collection<Integer> disjunctionList = CollectionUtils.disjunction(list, list2);
System.out.println(disjunctionList);
//獲取差集
Collection<Integer> subtractList = CollectionUtils.subtract(list, list2);
System.out.println(subtractList);
執(zhí)行結(jié)果:
[1, 2, 3, 4]
[2]
[1, 3, 4]
[1, 3]
說句實話猖腕,對兩個集合的操作,在實際工作中用得挺多的恨闪,特別是很多批量的場景中倘感。以前我們需要寫一堆代碼,但沒想到有現(xiàn)成的輪子咙咽。
3. Lists
如果你引入com.google.guava
的pom文件老玛,會獲得很多好用的小工具。這里推薦一款com.google.common.collect
包下的集合工具:Lists
钧敞。
它是在太好用了蜡豹,讓我愛不釋手。
3.1 創(chuàng)建空集合
有時候溉苛,我們想創(chuàng)建一個空集合余素。這時可以用Lists的newArrayList
方法,例如:
List<Integer> list = Lists.newArrayList();
3.2 快速初始化集合
有時候炊昆,我們想給一個集合中初始化一些元素桨吊。這時可以用Lists的newArrayList方法,例如:
List<Integer> list = Lists.newArrayList(1, 2, 3);
執(zhí)行結(jié)果:
[1, 2, 3]
3.3 笛卡爾積
如果你想將兩個集合做笛卡爾積
凤巨,Lists的cartesianProduct
方法可以幫你實現(xiàn):
List<Integer> list1 = Lists.newArrayList(1, 2, 3);
List<Integer> list2 = Lists.newArrayList(4,5);
List<List<Integer>> productList = Lists.cartesianProduct(list1,list2);
System.out.println(productList);
執(zhí)行結(jié)果:
[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
3.4 分頁
如果你想將一個大集合
分成若干個小集合
视乐,可以使用Lists的partition
方法:
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
List<List<Integer>> partitionList = Lists.partition(list, 2);
System.out.println(partitionList);
執(zhí)行結(jié)果:
[[1, 2], [3, 4], [5]]
這個例子中,list有5條數(shù)據(jù)敢茁,我將list集合按大小為2佑淀,分成了3頁,即變成3個小集合彰檬。
這個是我最喜歡的方法之一伸刃,經(jīng)常在項目中使用。
比如有個需求:現(xiàn)在有5000個id逢倍,需要調(diào)用批量用戶查詢接口捧颅,查出用戶數(shù)據(jù)。但如果你直接查5000個用戶较雕,單次接口響應(yīng)時間可能會非常慢碉哑。如果改成分頁處理,每次只查500個用戶亮蒋,異步調(diào)用10次接口扣典,就不會有單次接口響應(yīng)慢的問題。
3.5 流處理
如果我們想把某個集合轉(zhuǎn)換成另外一個接口慎玖,可以使用Lists的transform
方法贮尖。例如:
List<String> list = Lists.newArrayList("a","b","c");
List<String> transformList = Lists.transform(list, x -> x.toUpperCase());
System.out.println(transformList);
將小寫字母轉(zhuǎn)換成了大寫字母。
3.6 顛倒順序
Lists的有顛倒順序的方法reverse
趁怔。例如:
List<Integer> list = Lists.newArrayList(3, 1, 2);
List<Integer> reverseList = Lists.reverse(list);
System.out.println(reverseList);
執(zhí)行結(jié)果:
[2, 1, 3]
list的原始順序是312湿硝,使用reverse
方法顛倒順序之后闰蛔,變成了213。
Lists還有其他的好用的工具图柏,我在這里只是拋磚引玉序六,有興趣的朋友,可以仔細(xì)研究一下蚤吹。
4. Objects
在jdk7
之后例诀,提供了Objects
工具類,我們可以通過它操作對象裁着。
4.1 對象判空
在java中萬事萬物皆對象繁涂,對象的判空可以說無處不在。Objects的isNull
方法判斷對象是否為空二驰,而nonNull
方法判斷對象是否不為空扔罪。例如:
Integer integer = new Integer(1);
if (Objects.isNull(integer)) {
System.out.println("對象為空");
}
if (Objects.nonNull(integer)) {
System.out.println("對象不為空");
}
4.2 對象為空拋異常
如果我們想在對象為空時,拋出空指針異常桶雀,可以使用Objects的requireNonNull
方法矿酵。例如:
Integer integer1 = new Integer(128);
Objects.requireNonNull(integer1);
Objects.requireNonNull(integer1, "參數(shù)不能為空");
Objects.requireNonNull(integer1, () -> "參數(shù)不能為空");
4.3 判斷兩個對象是否相等
我們經(jīng)常需要判斷兩個對象是否相等,Objects給我們提供了equals
方法矗积,能非常方便的實現(xiàn):
Integer integer1 = new Integer(1);
Integer integer2 = new Integer(1);
System.out.println(Objects.equals(integer1, integer2));
執(zhí)行結(jié)果:
true
但使用這個方法有坑全肮,比如例子改成:
Integer integer1 = new Integer(1);
Long integer2 = new Long(1);
System.out.println(Objects.equals(integer1, integer2));
執(zhí)行結(jié)果:
false
具體原因不細(xì)說了。
4.4 獲取對象的hashCode
如果你想獲取某個對象的hashCode棘捣,可以使用Objects的hashCode
方法辜腺。例如:
String str = new String("abc");
System.out.println(Objects.hashCode(str));
執(zhí)行結(jié)果:
96354
Objects的內(nèi)容先介紹到這里,有興趣的小伙們乍恐,可以看看下面更多的方法:
5. BooleanUtils
在java中布爾值评疗,隨處可見。
如果你使用了布爾的包裝類:Boolean
茵烈,總感覺有點麻煩百匆,因為它有三種值:null
、true
瞧毙、false
胧华。我們在處理Boolean對象時,需要經(jīng)常判空宙彪。
頭疼!S星伞释漆!
但如果使用BooleanUtils
類處理布爾值,心情一下子就愉悅起來了篮迎。
5.1 判斷true或false
如果你想判斷某個參數(shù)的值是true或false男图,可以直接使用isTrue
或isFalse
方法示姿。例如:
Boolean aBoolean = new Boolean(true);
System.out.println(BooleanUtils.isTrue(aBoolean));
System.out.println(BooleanUtils.isFalse(aBoolean));
5.2 判斷不為true或不為false
有時候,需要判斷某個參數(shù)不為true逊笆,即是null或者false栈戳。或者判斷不為false难裆,即是null或者true子檀。
可以使用isNotTrue
或isNotFalse
方法。例如:
Boolean aBoolean = new Boolean(true);
Boolean aBoolean1 = null;
System.out.println(BooleanUtils.isNotTrue(aBoolean));
System.out.println(BooleanUtils.isNotTrue(aBoolean1));
System.out.println(BooleanUtils.isNotFalse(aBoolean));
System.out.println(BooleanUtils.isNotFalse(aBoolean1));
執(zhí)行結(jié)果:
false
true
true
true
5.3 轉(zhuǎn)換成數(shù)字
如果你想將true轉(zhuǎn)換成數(shù)字1乃戈,false轉(zhuǎn)換成數(shù)字0褂痰,可以使用toInteger
方法:
Boolean aBoolean = new Boolean(true);
Boolean aBoolean1 = new Boolean(false);
System.out.println(BooleanUtils.toInteger(aBoolean));
System.out.println(BooleanUtils.toInteger(aBoolean1));
執(zhí)行結(jié)果:
1
0
5.4 Boolean轉(zhuǎn)換成布爾值
我們有時候需要將包裝類Boolean
對象,轉(zhuǎn)換成原始的boolean
對象症虑,可以使用toBoolean
方法缩歪。例如:
Boolean aBoolean = new Boolean(true);
Boolean aBoolean1 = null;
System.out.println(BooleanUtils.toBoolean(aBoolean));
System.out.println(BooleanUtils.toBoolean(aBoolean1));
System.out.println(BooleanUtils.toBooleanDefaultIfNull(aBoolean1, false));
我們無需額外的判空了,而且還可以設(shè)置Boolean對象為空時返回的默認(rèn)值谍憔。
BooleanUtils類的方法還有很多匪蝙,有興趣的小伙伴可以看看下面的內(nèi)容:6. StringUtils
字符串
(String)在我們的日常工作中,用得非常非常非常多习贫。
在我們的代碼中經(jīng)常需要對字符串判空骗污,截取字符串、轉(zhuǎn)換大小寫沈条、分隔字符串需忿、比較字符串、去掉多余空格蜡歹、拼接字符串屋厘、使用正則表達式等等。
如果只用String類提供的那些方法月而,我們需要手寫大量的額外代碼汗洒,不然容易出現(xiàn)各種異常。
現(xiàn)在有個好消息是:org.apache.commons.lang3
包下的StringUtils
工具類父款,給我們提供了非常豐富的選擇溢谤。
6.1 字符串判空
其實空字符串,不只是null一種憨攒,還有""世杀," ","null"等等肝集,多種情況瞻坝。
StringUtils給我們提供了多個判空的靜態(tài)方法,例如:
String str1 = null;
String str2 = "";
String str3 = " ";
String str4 = "abc";
System.out.println(StringUtils.isEmpty(str1));
System.out.println(StringUtils.isEmpty(str2));
System.out.println(StringUtils.isEmpty(str3));
System.out.println(StringUtils.isEmpty(str4));
System.out.println("=====");
System.out.println(StringUtils.isNotEmpty(str1));
System.out.println(StringUtils.isNotEmpty(str2));
System.out.println(StringUtils.isNotEmpty(str3));
System.out.println(StringUtils.isNotEmpty(str4));
System.out.println("=====");
System.out.println(StringUtils.isBlank(str1));
System.out.println(StringUtils.isBlank(str2));
System.out.println(StringUtils.isBlank(str3));
System.out.println(StringUtils.isBlank(str4));
System.out.println("=====");
System.out.println(StringUtils.isNotBlank(str1));
System.out.println(StringUtils.isNotBlank(str2));
System.out.println(StringUtils.isNotBlank(str3));
System.out.println(StringUtils.isNotBlank(str4));
執(zhí)行結(jié)果:
true
true
false
false
=====
false
false
true
true
=====
true
true
true
false
=====
false
false
false
true
示例中的:isEmpty
杏瞻、isNotEmpty
所刀、isBlank
和isNotBlank
衙荐,這4個判空方法你們可以根據(jù)實際情況使用。
優(yōu)先推薦使用
isBlank
和isNotBlank
方法浮创,因為它會把" "
也考慮進去忧吟。
6.2 分隔字符串
分隔字符串是常見需求,如果直接使用String類的split方法斩披,就可能會出現(xiàn)空指針異常溜族。
String str1 = null;
System.out.println(StringUtils.split(str1,","));
System.out.println(str1.split(","));
執(zhí)行結(jié)果:
null
Exception in thread "main" java.lang.NullPointerException
at com.sue.jump.service.test1.UtilTest.main(UtilTest.java:21)
使用StringUtils的split方法會返回null,而使用String的split方法會報指針異常雏掠。
6.3 判斷是否純數(shù)字
給定一個字符串斩祭,判斷它是否為純數(shù)字,可以使用isNumeric
方法乡话。例如:
String str1 = "123";
String str2 = "123q";
String str3 = "0.33";
System.out.println(StringUtils.isNumeric(str1));
System.out.println(StringUtils.isNumeric(str2));
System.out.println(StringUtils.isNumeric(str3));
執(zhí)行結(jié)果:
true
false
false
6.4 將集合拼接成字符串
有時候摧玫,我們需要將某個集合的內(nèi)容,拼接成一個字符串绑青,然后輸出诬像,這時可以使用join
方法。例如:
List<String> list = Lists.newArrayList("a", "b", "c");
List<Integer> list2 = Lists.newArrayList(1, 2, 3);
System.out.println(StringUtils.join(list, ","));
System.out.println(StringUtils.join(list2, " "));
執(zhí)行結(jié)果:
a,b,c
1 2 3
當(dāng)然還有很多實用的方法闸婴,我在這里就不一一介紹了坏挠。[圖片上傳失敗...(image-27f33b-1659007130847)]
7. Assert
很多時候,我們需要在代碼中做判斷:如果不滿足條件邪乍,則拋異常降狠。
有沒有統(tǒng)一的封裝呢?
其實spring
給我們提供了Assert
類,它表示斷言
庇楞。
7.1 斷言參數(shù)是否為空
斷言參數(shù)
是否空榜配,如果不滿足條件,則直接拋異常吕晌。
String str = null;
Assert.isNull(str, "str必須為空");
Assert.isNull(str, () -> "str必須為空");
Assert.notNull(str, "str不能為空");
如果不滿足條件就會拋出IllegalArgumentException
異常蛋褥。
7.2 斷言集合是否為空
斷言集合
是否空,如果不滿足條件睛驳,則直接拋異常烙心。
List<String> list = null;
Map<String, String> map = null;
Assert.notEmpty(list, "list不能為空");
Assert.notEmpty(list, () -> "list不能為空");
Assert.notEmpty(map, "map不能為空");
如果不滿足條件就會拋出IllegalArgumentException
異常。
7.3 斷言條件是否為空
斷言是否滿足某個條件
乏沸,如果不滿足條件淫茵,則直接拋異常。
List<String> list = null;
Assert.isTrue(CollectionUtils.isNotEmpty(list), "list不能為空");
Assert.isTrue(CollectionUtils.isNotEmpty(list), () -> "list不能為空");
當(dāng)然Assert類還有一些其他的功能屎蜓,這里就不多介紹了痘昌。
8. IOUtils
IO
流在我們?nèi)粘9ぷ髦幸灿玫帽容^多,盡管java已經(jīng)給我們提供了豐富的API炬转。
但我們不得不每次讀取文件辆苔,或者寫入文件之后,寫一些重復(fù)的的代碼扼劈。手動在finally
代碼塊中關(guān)閉流驻啤,不然可能會造成內(nèi)存溢出
。
有個好消息是:如果你使用org.apache.commons.io
包下的IOUtils
類荐吵,會節(jié)省大量的時間骑冗。
8.1 讀取文件
如果你想將某個txt文件中的數(shù)據(jù),讀取到字符串當(dāng)中先煎,可以使用IOUtils類的toString
方法贼涩。例如:
String str = IOUtils.toString(new FileInputStream("/temp/a.txt"), StandardCharsets.UTF_8);
System.out.println(str);
8.2 寫入文件
如果你想將某個字符串的內(nèi)容,寫入到指定文件當(dāng)中薯蝎,可以使用IOUtils類的write
方法遥倦。例如:
String str = "abcde";
IOUtils.write(str, new FileOutputStream("/temp/b.tx"), StandardCharsets.UTF_8);
8.3 文件拷貝
如果你想將某個文件中的所有內(nèi)容,都拷貝到另一個文件當(dāng)中占锯,可以使用IOUtils類的copy
方法袒哥。例如:
IOUtils.copy(new FileInputStream("/temp/a.txt"), new FileOutputStream("/temp/b.txt"));
8.4 讀取文件內(nèi)容到字節(jié)數(shù)組
如果你想將某個文件中的內(nèi)容,讀取字節(jié)數(shù)組中消略,可以使用IOUtils類的toByteArray
方法堡称。例如:
byte[] bytes = IOUtils.toByteArray(new FileInputStream("/temp/a.txt"));
IOUtils類非常實用,感興趣的小伙們艺演,可以看看下面內(nèi)容却紧。
9. MDC
MDC
是org.slf4j
包下的一個類,它的全稱是Mapped Diagnostic Context胎撤,我們可以認(rèn)為它是一個線程安全的存放診斷日志的容器晓殊。
MDC的底層是用了ThreadLocal
來保存數(shù)據(jù)的。
我們可以用它傳遞參數(shù)哩照。
例如現(xiàn)在有這樣一種場景:我們使用RestTemplate
調(diào)用遠程接口時挺物,有時需要在header
中傳遞信息,比如:traceId飘弧,source等识藤,便于在查詢?nèi)罩緯r能夠串聯(lián)一次完整的請求鏈路,快速定位問題次伶。
這種業(yè)務(wù)場景就能通過ClientHttpRequestInterceptor
接口實現(xiàn)痴昧,具體做法如下:
第一步,定義一個LogFilter攔截所有接口請求冠王,在MDC中設(shè)置traceId:
public class LogFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
MdcUtil.add(UUID.randomUUID().toString());
System.out.println("記錄請求日志");
chain.doFilter(request, response);
System.out.println("記錄響應(yīng)日志");
}
@Override
public void destroy() {
}
}
第二步赶撰,實現(xiàn)ClientHttpRequestInterceptor
接口,MDC中獲取當(dāng)前請求的traceId,然后設(shè)置到header中:
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().set("traceId", MdcUtil.get());
return execution.execute(request, body);
}
}
第三步豪娜,定義配置類餐胀,配置上面定義的RestTemplateInterceptor
類:
@Configuration
public class RestTemplateConfiguration {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Collections.singletonList(restTemplateInterceptor()));
return restTemplate;
}
@Bean
public RestTemplateInterceptor restTemplateInterceptor() {
return new RestTemplateInterceptor();
}
}
其中MdcUtil其實是利用MDC工具在ThreadLocal中存儲和獲取traceId
public class MdcUtil {
private static final String TRACE_ID = "TRACE_ID";
public static String get() {
return MDC.get(TRACE_ID);
}
public static void add(String value) {
MDC.put(TRACE_ID, value);
}
}
當(dāng)然,這個例子中沒有演示MdcUtil類的add方法具體調(diào)的地方瘤载,我們可以在filter中執(zhí)行接口方法之前否灾,生成traceId,調(diào)用MdcUtil類的add方法添加到MDC中鸣奔,然后在同一個請求的其他地方就能通過MdcUtil類的get方法獲取到該traceId墨技。
能使用MDC保存traceId等參數(shù)的根本原因是,用戶請求到應(yīng)用服務(wù)器挎狸,Tomcat會從線程池中分配一個線程去處理該請求扣汪。
那么該請求的整個過程中,保存到MDC的ThreadLocal中的參數(shù)锨匆,也是該線程獨享的崭别,所以不會有線程安全問題。
10. ClassUtils
spring的org.springframework.util
包下的ClassUtils
類统刮,它里面有很多讓我們驚喜的功能紊遵。
它里面包含了類和對象相關(guān)的很多非常實用的方法。
10.1 獲取對象的所有接口
如果你想獲取某個對象的所有接口侥蒙,可以使用ClassUtils的getAllInterfaces
方法暗膜。例如:
Class<?>[] allInterfaces = ClassUtils.getAllInterfaces(new User());
10.2 獲取某個類的包名
如果你想獲取某個類的包名,可以使用ClassUtils的getPackageName
方法鞭衩。例如:
String packageName = ClassUtils.getPackageName(User.class);
System.out.println(packageName);
10.3 判斷某個類是否內(nèi)部類
如果你想判斷某個類是否內(nèi)部類学搜,可以使用ClassUtils的isInnerClass
方法。例如:
System.out.println(ClassUtils.isInnerClass(User.class));
10.4 判斷對象是否代理對象
如果你想判斷對象是否代理對象论衍,可以使用ClassUtils的isCglibProxy
方法瑞佩。例如:
System.out.println(ClassUtils.isCglibProxy(new User()));
ClassUtils還有很多有用的方法,等待著你去發(fā)掘坯台。感興趣的朋友炬丸,可以看看下面內(nèi)容:
11. BeanUtils
spring給我們提供了一個JavaBean
的工具類,它在org.springframework.beans
包下面蜒蕾,它的名字叫做:BeanUtils
稠炬。
讓我們一起看看這個工具可以帶給我們哪些驚喜走越。
11.1 拷貝對象的屬性
曾幾何時狈癞,你有沒有這樣的需求:把某個對象中的所有屬性,都拷貝到另外一個對象中驻龟。這時就能使用BeanUtils的copyProperties
方法撤摸。例如:
User user1 = new User();
user1.setId(1L);
user1.setName("蘇三說技術(shù)");
user1.setAddress("成都");
User user2 = new User();
BeanUtils.copyProperties(user1, user2);
System.out.println(user2);
11.2 實例化某個類
如果你想通過反射實例化一個類的對象毅桃,可以使用BeanUtils的instantiateClass
方法褒纲。例如:
User user = BeanUtils.instantiateClass(User.class);
System.out.println(user);
11.3 獲取指定類的指定方法
如果你想獲取某個類的指定方法,可以使用BeanUtils的findDeclaredMethod
方法钥飞。例如:
Method declaredMethod = BeanUtils.findDeclaredMethod(User.class, "getId");
System.out.println(declaredMethod.getName());
11.4 獲取指定方法的參數(shù)
如果你想獲取某個方法的參數(shù)莺掠,可以使用BeanUtils的findPropertyForMethod
方法。例如:
Method declaredMethod = BeanUtils.findDeclaredMethod(User.class, "getId");
PropertyDescriptor propertyForMethod = BeanUtils.findPropertyForMethod(declaredMethod);
System.out.println(propertyForMethod.getName());
如果你對BeanUtils比較感興趣代承,可以看看下面內(nèi)容:
12. ReflectionUtils
有時候汁蝶,我們需要在項目中使用反射
功能渐扮,如果使用最原始的方法來開發(fā)论悴,代碼量會非常多,而且很麻煩墓律,它需要處理一大堆異常以及訪問權(quán)限等問題膀估。
好消息是spring給我們提供了一個ReflectionUtils
工具,它在org.springframework.util
包下面耻讽。
12.1 獲取方法
如果你想獲取某個類的某個方法察纯,可以使用ReflectionUtils類的findMethod
方法。例如:
Method method = ReflectionUtils.findMethod(User.class, "getId");
12.2 獲取字段
如果你想獲取某個類的某個字段针肥,可以使用ReflectionUtils類的findField
方法饼记。例如:
Field field = ReflectionUtils.findField(User.class, "id");
12.3 執(zhí)行方法
如果你想通過反射調(diào)用某個方法,傳遞參數(shù)慰枕,可以使用ReflectionUtils類的invokeMethod
方法具则。例如:
ReflectionUtils.invokeMethod(method, springContextsUtil.getBean(beanName), param);
12.4 判斷字段是否常量
如果你想判斷某個字段是否常量,可以使用ReflectionUtils類的isPublicStaticFinal
方法具帮。例如:
Field field = ReflectionUtils.findField(User.class, "id");
System.out.println(ReflectionUtils.isPublicStaticFinal(field));
12.5 判斷是否equals方法
如果你想判斷某個方法是否equals方法博肋,可以使用ReflectionUtils類的isEqualsMethod
方法。例如:
Method method = ReflectionUtils.findMethod(User.class, "getId");
System.out.println(ReflectionUtils.isEqualsMethod(method));
當(dāng)然這個類還有不少有趣的方法蜂厅,感興趣的朋友匪凡,可以看看下面內(nèi)容:
13. Base64Utils
有時候,為了安全考慮掘猿,需要將參數(shù)只用base64
編碼病游。
這時就能直接使用org.springframework.util
包下的Base64Utils
工具類。
它里面包含:encode
和decode
方法稠通,用于對數(shù)據(jù)進行加密和解密衬衬。例如:
String str = "abc";
String encode = new String(Base64Utils.encode(str.getBytes()));
System.out.println("加密后:" + encode);
try {
String decode = new String(Base64Utils.decode(encode.getBytes()), "utf8");
System.out.println("解密后:" + decode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
執(zhí)行結(jié)果:
加密后:YWJj
解密后:abc
14. StandardCharsets
我們在做字符轉(zhuǎn)換的時候,經(jīng)常需要指定字符編碼采记,比如:UTF-8佣耐、ISO-8859-1等等。
這時就可以直接使用java.nio.charset
包下的StandardCharsets
類中靜態(tài)變量唧龄。
例如:
String str = "abc";
String encode = new String(Base64Utils.encode(str.getBytes()));
System.out.println("加密后:" + encode);
String decode = new String(Base64Utils.decode(encode.getBytes())
, StandardCharsets.UTF_8);
System.out.println("解密后:" + decode);
15. DigestUtils
有時候兼砖,我們需要對數(shù)據(jù)進行加密處理奸远,比如:md5或sha256。
可以使用apache的org.apache.commons.codec.digest
包下的DigestUtils
類讽挟。
15.1 md5加密
如果你想對數(shù)據(jù)進行md5加密懒叛,可以使用DigestUtils的md5Hex
方法。例如:
String md5Hex = DigestUtils.md5Hex("蘇三說技術(shù)");
System.out.println(md5Hex);
15.2 sha256加密
如果你想對數(shù)據(jù)進行sha256加密耽梅,可以使用DigestUtils的sha256Hex
方法薛窥。例如:
String md5Hex = DigestUtils.sha256Hex("蘇三說技術(shù)");
System.out.println(md5Hex);
當(dāng)然這個工具還有很多其他的加密方法:
16. SerializationUtils
有時候,我們需要把數(shù)據(jù)進行序列化
和反序列化
處理眼姐。
傳統(tǒng)的做法是某個類實現(xiàn)Serializable
接口诅迷,然后重新它的writeObject
和readObject
方法。
但如果使用org.springframework.util
包下的SerializationUtils
工具類众旗,能更輕松實現(xiàn)序列化和反序列化功能罢杉。例如:
Map<String, String> map = Maps.newHashMap();
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
byte[] serialize = SerializationUtils.serialize(map);
Object deserialize = SerializationUtils.deserialize(serialize);
System.out.println(deserialize);
17. HttpStatus
很多時候,我們會在代碼中定義http的返回碼贡歧,比如:接口正常返回200滩租,異常返回500,接口找不到返回404利朵,接口不可用返回502等律想。
private int SUCCESS_CODE = 200;
private int ERROR_CODE = 500;
private int NOT_FOUND_CODE = 404;
其實org.springframework.http
包下的HttpStatus枚舉,或者org.apache.http
包下的HttpStatus
接口绍弟,已經(jīng)把常用的http返回碼給我們定義好了技即,直接拿來用就可以了,真的不用再重復(fù)定義了晌柬。
好了姥份,今天的內(nèi)容分享到這里。