notebook icon indicating copy to clipboard operation
notebook copied to clipboard

FC2: 简化java中令人头疼的判空、判等

Open sunwu51 opened this issue 5 years ago • 2 comments

java总遇到对象为null,此时不论是调用方法还是属性都会产生空指针异常。需要写if(obj != null)这样的判断。

我们写java的时候,经常遇到以下几个问题。

  • 1 对于字符串除了判null,还要判空串。

  • 2 对于集合对象例如list、set还要判断是否是0个元素的空集合。

  • 3 判断两个对象是否equals的时候,一定不为null的最好放在前面,例如不要写a.equals("字符串"),而要写"字符串".equals(a),但如果俩对象都不知道是不是null可能就需要这样

if(a != null && a.equals(b)){
  xxx
} 

使用apache commons包提供的工具,可以少写一些代码,这个工具包把很多常用的功能进行了封装。
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.11</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

例如

// 1 如果字符串str是null,或者空字符串,则返回true
StringUtils.isEmpty(str);

// 2 如果str是null,空字符串,或只含有空格的字符串,则返回true
StringUtils.isBlank(str);

// 3 如果list是null或者是空的则返回true,可以接收list set等集合类
CollectionUtils.isEmpty(list);

// 4 两个对象都不为null且equals,或者俩对象都是null,则返回true,否则是false。
// Objects不是第三方包,是java7之后引入到jdk中的,可以直接使用,java7之前也可以使用guava中的Objects,用法一样。
Objects.equals(obj1, obj2);

小结与拓展

我们可以使用工具类封好的判断方法,来简化变量的判断相等。当然仔细研究下这些工具库,就会发现除了判断相等还封装了很多常用的方法。

这样的工具包其实很多,就单说apache commons除了上面提到的langcollections还有IO,BeanUtils,loggingCSV等等参考,此外谷歌的guava也有很多类似的工具类的封装。

sunwu51 avatar Jul 19 '20 15:07 sunwu51

新开项目必导的工具包

liaoshuguang avatar Dec 26 '23 10:12 liaoshuguang

邮件已收到,我会尽快查看

anan-2019 avatar Dec 26 '23 10:12 anan-2019

邮件已收到,我会尽快查看

anan-2019 avatar Aug 26 '24 06:08 anan-2019