前言 在java的龐大體系中,其實有很多不錯的小工具,也就是我們平常說的:輪子
。
如果在我們的日常工作當中,能夠?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 )
當然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還有其他的好用的工具,我在這里只是拋磚引玉,有興趣的朋友,可以仔細研究一下。
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
具體原因不細說了,有興趣的小伙們可以看看我的另一篇文章《Objects.equals有坑 》,里面有非常詳細的講解。
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)常判空。
頭疼?。?!
但如果使用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對象為空時返回的默認值。
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,c1 2 3
當然還有很多實用的方法,我在這里就不一一介紹了。
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不能為空' );
當然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ù),讀取到字符串當中,可以使用IOUtils類的toString
方法。例如:
String str = IOUtils.toString(new FileInputStream('/temp/a.txt' ), StandardCharsets.UTF_8); System.out.println(str);
8.2 寫入文件 如果你想將某個字符串的內(nèi)容,寫入到指定文件當中,可以使用IOUtils類的write
方法。例如:
String str = 'abcde' ; IOUtils.write(str, new FileOutputStream('/temp/b.tx' ), StandardCharsets.UTF_8);
8.3 文件拷貝 如果你想將某個文件中的所有內(nèi)容,都拷貝到另一個文件當中,可以使用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,我們可以認為它是一個線程安全的存放診斷日志的容器。
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中獲取當前請求的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); } }
當然,這個例子中沒有演示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));
當然這個類還有不少有趣的方法,感興趣的朋友,可以看看下面內(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);
當然這個工具還有很多其他的加密方法:
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)容分享到這里。
如果覺得這篇文章對你有些幫助的話,麻煩給我點個贊喔,謝謝你的支持。