Java高级技术后端技术Java后端必备

高段位、不造轮子(善用工具类)

2018-10-17  本文已影响2人  关捷

使用大众的语言,交流才会有默契。写代码亦如此!不要乱造轮子,积累轮子,搞懂轮子,最终站在巨人的肩上,才是正途。

字符串操作

org.apache.commons.lang3.StringUtils中几乎有你要的所有字符串操作。
例如:Empty(空判断)、Blank(空白字符判断)、truncate(保留部分长度)、左右保留、左右追加、trim(去掉首位字符ASCII码小于32)、strip(去掉首位空白字符或指定字符)、重复、拼接、分割等等。

如果你需要获取两个字符串的共同前缀共同后缀com.google.common.base.Strings中你可以找到想要的。

如果你需要根据组合复杂条件进行字符筛选,过滤,删除等操作,com.google.common.base.CharMatcher是不错的选择,例如:

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

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

 //new一个有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一个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-空 

记住一条,对null没有默认处理,不要想当然,需要格外注意,例如:

 //StringBuilder会把null元素转换为值为null的字符串
System.out.println(new StringBuilder().append((String) null).append('-').append("a")); //null-a

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

如果想要对字符串进行分割,最好不要使用StringUtils.split(),因为它的规则不够清晰,而是要用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)常量

不要纠结于选择,来点默契,定个约定:
优先选择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
如果需要指定瞬间进行初始化,可以使用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就不要再让它出现了!

数字操作

不能不识:org.apache.commons.lang3.math.NumberUtils
提供了很多常用的基本类型包装类的常量,以及很多便捷操作:

随机生成器

字符串随机生成,可以使用:
org.apache.commons.lang3.RandomStringUtils
注意:如果要生成只包含数字的字符串,
不能使用: RandomStringUtils.randomNumeric(int)
而要使用: RandomStringUtils.random(int, "0123456789")
因为性能有近10倍差距,至于为什么?自行研究。

随机数生成工具
org.apache.commons.lang3.RandomUtils
简单易用,就不多说。

反射

三个常见工具类:

通过ClassUtils可以获取所有接口、所有的父类、获取数组每个元素类型Class<?>[] toClass(final Object... array)等等;
通过FieldUtils可以方便的属性操作:查、读、写;
通过MethodUtils可以方便方法操作:获取、调用。
通过工具类,可以饶过JDK方法、字段反射操作的限制,例如:不会自动遍历所有父类等等。

如果需要遍历所有字段或方法进行某种操作,可以使用:
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)

判断访问权限,可以使用java.lang.reflect.Modifier,当然你可能永远不会使用。

获取Springbean的目标对象,可以使用: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

IO操作

主要2个工具类:

IOUtils包括便捷的流操作,包括:优雅关闭流closeQuietly(),当然jdk7后使用try-with-resource自动关闭、复制、转化、常量(换号符、路径分割符等)等等

FileUtils提供文件便捷操作,文件夹遍历、文件复制读写、转换等等。

总之,你几乎以后都不需要自己实例化InputStream、Reader等jdk底层实现了。

集合操作

集合、可谓乱象丛生。各种同质化工具类以及guava,common包等提供的特殊集合。其实你要记住的只是常用操作而已,乱七八糟的东西私下研究研究、涨涨见识就行了。

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
注意:正常情况,返回值应该是空集合而不是null。

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

4. 基本类型数组转集合
com.google.common.primitives.Ints.asList(int... )
com.google.common.primitives.Longs.asList(long...)
...
不要用java.util.Arrays.asList,它会认为数组是一个对象。

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() //分割大集合,并发处理是常用
com.google.common.collect.Lists.transform()
//懒式数据转换,正真get数据时才会转换。
java.util.Collections.max(java.util.Collection<? extends T>) //最大
java.util.Collections.min(java.util.Collection<? extends T>)//最小

先就写到这里,已经比较多了,以后用到在补充,如果哪位同学给点补充就再好不过了。

上一篇下一篇

猜你喜欢

热点阅读