高段位、不造輪子(善用工具類)

使用大眾的語言,交流才會(huì)有默契。寫代碼亦如此!不要亂造輪子,積累輪子,搞懂輪子,最終站在巨人的肩上,才是正途。

字符串操作

org.apache.commons.lang3.StringUtils中幾乎有你要的所有字符串操作。
例如:Empty(空判斷)、Blank(空白字符判斷)、truncate(保留部分長(zhǎng)度)、左右保留、左右追加、trim(去掉首位字符ASCII碼小于32)、strip(去掉首位空白字符或指定字符)、重復(fù)、拼接、分割等等。

如果你需要獲取兩個(gè)字符串的共同前(后)綴nullToEmpty操作,com.google.common.base.Strings中你可以找到想要的。

如果你需要根據(jù)組合復(fù)雜條件進(jìn)行字符篩選,過濾,刪除等操作,com.google.common.base.CharMatcher是不錯(cuò)的選擇,例如:

CharMatcher charMatcher = CharMatcher.inRange('0', '9').or(CharMatcher.inRange('a', 'b'));
System.out.println(charMatcher.retainFrom("abcd123dd")); //ab123
System.out.println(charMatcher.removeFrom("abcd123dd")); //cddd

千萬記住,如果能夠使用字符操作,盡量不要用字符串正則匹配,因?yàn)樾阅懿钜粋€(gè)量級(jí),例如:

//三個(gè)方法同樣的效果,我機(jī)器上第一個(gè)方法性能差10倍
String uuid = UUID.randomUUID().toString();
System.out.println(StringUtils.removeAll(uuid, "-"));
System.out.println(StringUtils.remove(uuid, '-'));
System.out.println(CharMatcher.is('-').removeFrom(uuid));

如果需要連接成字符串的集合中有元素為null,那你就要小心了,你可能需要com.google.common.base.Joiner。例如:

 //new一個(gè)有null元素的ArrayList
List list = Lists.newArrayList(new Integer(1), new Integer(2), null, new Integer(3));  
System.out.println(StringUtils.join(list.iterator(), ',')); //1,2,,3
System.out.println(Joiner.on(',').skipNulls().join(list)); //1,2,3
//System.out.println(Joiner.on(',').join(list)); //空指針

//new一個(gè)key或者value是null的Map
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", null);
map.put(null, 3);
System.out.println(Joiner.on(',').withKeyValueSeparator('-').useForNull("空").join(map)); //空-3,a-1,b-空 

記住一條,對(duì)null沒有默認(rèn)處理,不要想當(dāng)然,需要格外注意,例如:

 //StringBuilder會(huì)把null元素轉(zhuǎn)換為值為null的字符串
System.out.println(new StringBuilder().append((String) null).append('-').append("a")); //null-a

注意:字符串+就是 StringBuilder.append()

如果想要對(duì)字符串進(jìn)行分割,最好不要使用StringUtils.split(),因?yàn)樗囊?guī)則不夠清晰,而是要用com.google.common.base.Splitter,例如:

String param = ", ,a,b  ,";
System.out.println(Arrays.toString(StringUtils.split(param, ','))); //[ , a, b  ]
System.out.println(Splitter.on(',').omitEmptyStrings().trimResults().splitToList(param)); //[a, b]

字符編碼(Charset)常量

不要糾結(jié)于選擇,來點(diǎn)默契,定個(gè)約定:
優(yōu)先選擇com.google.common.base.Charsets
上面沒有引入就選org.apache.commons.codec.Charsets
最后jdk1.8才有的java.nio.charset.StandardCharsets

日期處理

日期增、減、字符串解析成Date,可以使用
org.apache.commons.lang3.time.DateUtils
日期格式化成字符串,可以使用
org.apache.commons.lang3.time.DateFormatUtils
如果需要指定瞬間進(jìn)行日期時(shí)間初始化,可以使用org.joda.time.DateTime,例如:

System.out.println(new DateTime(2018, 12, 1, 13, 1, 1).toDate()); //Sat Dec 01 13:01:01 CST 2018

另外,SimpleDateFormat就不要再讓它出現(xiàn)了!

數(shù)字操作

不能不識(shí):org.apache.commons.lang3.math.NumberUtils
提供了很多常用的基本類型包裝類的常量,以及很多便捷操作:

  • 字符串轉(zhuǎn)數(shù)字失敗返回默認(rèn)值
    NumberUtils.toInt(java.lang.String, int)
    NumberUtils.toLong(java.lang.String, int)
    ......
    提供所有基本類型數(shù)字操作方法,也有參數(shù)是一個(gè)的方法,默認(rèn)值則是0,如果你不想轉(zhuǎn)換拋出異常,就不要用原生API。
  • 返回最大或最小
    NumberUtils.max(...)
    NumberUtils.min(...)
    支持所有的基本類型數(shù)組,當(dāng)然如果你只有2個(gè)值比較, 下面方式可能會(huì)更好:
    java.lang.Math.max(x, y)
    java.lang.Math.min(x, y)

隨機(jī)生成器

字符串隨機(jī)生成,可以使用:
org.apache.commons.lang3.RandomStringUtils
注意:如果要生成只包含數(shù)字的字符串,
不能使用: RandomStringUtils.randomNumeric(int)
而要使用: RandomStringUtils.random(int, "0123456789")
因?yàn)樾阅苡薪?0倍差距,至于為什么?自行研究。

隨機(jī)數(shù)生成工具
org.apache.commons.lang3.RandomUtils
簡(jiǎn)單易用,就不多說。

反射

三個(gè)常見工具類:

  • org.apache.commons.lang3.ClassUtils
  • org.apache.commons.lang3.reflect.FieldUtils
  • org.apache.commons.lang3.reflect.MethodUtils

通過ClassUtils可以獲取所有接口、所有的父類等類定義相關(guān)的操作,也可以獲取數(shù)組每個(gè)元素類型,例如:Class<?>[] toClass(final Object... array)。
通過FieldUtils可以方便的屬性操作:查、讀、寫;
通過MethodUtils可以方便方法操作:獲取、調(diào)用。
通過工具類,可以饒過JDK方法、字段反射操作的限制。具體可以參考:JAVA反射,用好就這點(diǎn)東西

如果需要遍歷所有字段或方法進(jìn)行某種操作,可以使用:
org.springframework.util.ReflectionUtils,例如:

doWithMethods(Class<?> clazz, MethodCallback mc)
doWithLocalMethods(Class<?> clazz, MethodCallback mc) 
doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf) 
doWithFields(Class<?> clazz, FieldCallback fc) 
doWithLocalFields(Class<?> clazz, FieldCallback fc)
doWithFields(Class<?> clazz, FieldCallback fc, FieldFilter ff)

ReflectionUtils這個(gè)類我在RPC中動(dòng)態(tài)代理中有使用。

判斷訪問權(quán)限,可以使用java.lang.reflect.Modifier,當(dāng)然你可能永遠(yuǎn)不會(huì)使用。

獲取Springbean的目標(biāo)對(duì)象,可以使用:org.springframework.aop.framework.AopProxyUtils.ultimateTargetClass()
主要功能:如果是cglib生成的代理類,則返回父類。

注解操作

獲取注解,判斷是否有注解等,使用
org.springframework.core.annotation.AnnotationUtils

序列化工具

org.apache.commons.lang3.SerializationUtils,例如:

byte[] bytes = SerializationUtils.serialize(new Integer(1));
System.out.println(SerializationUtils.<Integer>deserialize(bytes)); //1

摘要(簽名)工具類

org.apache.commons.codec.digest.DigestUtils
支持常用的md5/sha1/sha256等等單向散列摘要算法,使用:

DigestUtils.md5("abc"); //900150983cd24fb0d6963f7d28e17f72
DigestUtils.sha256("abc"); //ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

IO操作

主要2個(gè)工具類:

  • org.apache.commons.io.IOUtils
  • org.apache.commons.io.FileUtils

IOUtils包括便捷的流操作,包括:優(yōu)雅關(guān)閉流closeQuietly(),當(dāng)然jdk7后使用try-with-resource自動(dòng)關(guān)閉、復(fù)制、轉(zhuǎn)化、讀取、寫入、常量(換號(hào)符、路徑分割符等)等等。
FileUtils提供文件便捷操作,文件夾遍歷、文件復(fù)制讀寫、轉(zhuǎn)換等等。
例如:

FileUtils.readFileToString(new File("***"), Charsets.UTF_8)
IOUtils.toString(java.io.InputStream,java.nio.charset.Charse)
IOUtils.copy(final Reader input, final Writer output)
......

總之,你幾乎以后都不需要自己實(shí)例化InputStream、Reader等jdk底層實(shí)現(xiàn)了。

集合操作

集合,可謂亂象叢生。各種同質(zhì)化工具類以及guava,common包等提供的特殊集合。其實(shí)你要記住的只是常用操作而已,亂七八糟的東西私下研究研究、漲漲見識(shí)就行了。

1. 判空
org.apache.commons.collections.CollectionUtils.isEmpty()
org.apache.commons.collections.MapUtils.isEmpty()

2. 常量
java.util.Collections.EMPTY_LIST
java.util.Collections.EMPTY_MAP
java.util.Collections.EMPTY_SET
注意:正常情況,返回值應(yīng)該是空集合而不是null。

3. 單元素轉(zhuǎn)集合
java.util.Arrays.asList()返回的集合不支持add、remove操作
com.google.common.collect.Lists.newArrayList(E...)
com.google.common.collect.Sets.newHashSet(E...)

4. 基本類型數(shù)組轉(zhuǎn)集合
com.google.common.primitives.Ints.asList(int... )
com.google.common.primitives.Longs.asList(long...)
......
不要用java.util.Arrays.asList,它會(huì)認(rèn)為數(shù)組是一個(gè)對(duì)象。

5. 常用操作
java.util.Collections.sort(java.util.List<T>, java.util.Comparator<? super T>)//排序
org.apache.commons.collections.ListUtils.retainAll(Collection collection, Collection retain)//保留交集
org.apache.commons.collections.ListUtils.removeAll(Collection collection, Collection remove) //去掉相交
com.google.common.collect.Lists.partition() 或者
org.apache.commons.collections4.ListUtils.partition() //分割大集合,并發(fā)處理時(shí)很常用
com.google.common.collect.Lists.transform()
//懶式數(shù)據(jù)轉(zhuǎn)換,正真get數(shù)據(jù)時(shí)才會(huì)轉(zhuǎn)換。
java.util.Collections.max(java.util.Collection<? extends T>) //最大
java.util.Collections.min(java.util.Collection<? extends T>)//最小

先就寫到這里,已經(jīng)比較多了,以后用到在補(bǔ)充,如果哪位同學(xué)給點(diǎn)補(bǔ)充就再好不過了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容