Java中空指针异常的判断和断言处理

实体类

//实体类为null
ItemDTO itemDTO = null;
//判断方式
//方式1 
itemDTO == null | itemDTO != null
//方式2,import java.util.Objects;
Objects.isNull(itemDTO) | Objects.nonNull(itemDTO)  

字符串

String str = "";
String str1 = "   ";
String str2 = null;
//判断方式
//方式1
str2 == null  || str2.equals("")  |  str2 != null  && !str2.equals("") 
//方式2
str == null || str.trim().equals("")   |  str2 != null && !str2.trim().equals("")
//方式3,import org.apache.commons.lang.StringUtils;
StringUtils.isEmpty(str1)  |  StringUtils.isNotEmpty(str1)
//方式4,import org.apache.commons.lang.StringUtils; 
StringUtils.isBlank(str1)  |  StringUtils.isNotBlank(str1)

isBlank和isEmpty的区别:

可以这样理解,isBlank是人类逻辑的判空,str1被判定为空,isEmpty是机器逻辑判空,str1被判定为非空

List

List<ItemDTO> list = new ArrayList<>();
List<ItemDTO> list1 = Collections.emptyList();
List<ItemDTO> list2 = null;
//判断方式
//方式1
list == null || list.isEmpty()  |  list != null && !list.isEmpty()
//方式2,import org.springframework.util.CollectionUtils;
CollectionUtils.isEmpty(list)    

Map

Map<String,ItemDTO> map = new HashMap<>();
Map<String, ItemDTO> map1 = Collections.emptyMap();
Map<String, ItemDTO> map2 = null;
//判断方式
//方式1
map2 == null || map2.isEmpty()  |  map2 != null && !map2.isEmpty()
//方式2,import org.springframework.util.CollectionUtils;
CollectionUtils.isEmpty(map)   

处理方式之一(断言)

//写法1,java内置无需引包
assert itemDTO == null : "itemDTO is null";  
//写法2,import org.springframework.util.Assert;
Assert.isNull(itemDTO,"itemDTO is null");    
//断言等价于:
if(Objects.nonNull(itemDTO)){
                throw new AssertionError("itemDTO is null");
            }
总结:处理空指针的时候如果要以抛异常这种方式处理可以使用断言

总结:

一般项目中都有自己的工具类,还有很多工具包中都有各种方法去处理这些问题,如果不使用工具类需要注意判断null的要写在前面,某些情况下如果有使用到equals,使用"".equals(str)比str.equals("")更好

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值