实体类
//实体类为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("")更好