Java判空小细节
一、问题
问题:我们新增数据的时候,我们将新增接口与更新接口融合在同一个接口,使用Mybatis-plus的saveOrUpdate接口,进行新增
二、代码:
代码如下:
public Boolean save(CalculationTypeDTO calculationTypeDTO) {
CalculationType calculationType = new CalculationType();
BeanUtils.copyProperties(calculationTypeDTO, calculationType);
//新增接口
if(calculationTypeDTO.getId().isEmpty()) {
calculationType.setDeleted(Constant.NOT_DELETE);
}else{
calculationType.setCreateTime(new Date());
}
calculationType.setUpdateTime(new Date());
return saveOrUpdate(calculationType);
}
当我们调用接口的时候,响应数据如下:
控制台也不报错,debug调试,发现,新增数据的时候根本没有进入if条件中去
三、下面是新增时的json数据:
问题所在:当我们新增数据的时候,没有传入id值,此时id:null;我们点入isEmpty方法后查看底层代码
/**
* Returns {@code true} if, and only if, {@link #length()} is {@code 0}.
*
* @return {@code true} if {@link #length()} is {@code 0}, otherwise
* {@code false}
*
* @since 1.6
*/
public boolean isEmpty() {
return value.length == 0;
}
四、分析
null是不能使用isEmpty()函数进行判断,压根不能进入方法,只能报异常了
五、解决
我们在判断字符串是否为空的时候,先进行判空处理,即可,或者直接判空就行
CalculationType calculationType = new CalculationType();
BeanUtils.copyProperties(calculationTypeDTO, calculationType);
//新增接口
if(calculationTypeDTO.getId() == null) {
// if(calculationTypeDTO.getId() == null || calculationTypeDTO.getId().isEmpty()) {
calculationType.setDeleted(Constant.NOT_DELETE);
}else{
calculationType.setCreateTime(new Date());
}
calculationType.setUpdateTime(new Date());
return saveOrUpdate(calculationType);