使用BeanUtils.copyProperties报错Source must not be null java.lang.IllegalArgumentException: Source must not be null
时间: 2024-02-23 20:53:52 浏览: 44
使用BeanUtils.copyProperties报错"Source must not be null java.lang.IllegalArgumentException: Source must not be null"的原因是源对象为null。在调用BeanUtils.copyProperties方法时,源对象不能为空,否则会抛出该异常。
解决该问题的方法是在调用BeanUtils.copyProperties方法之前,先判断源对象是否为null。如果源对象为null,则不进行copy操作,直接返回null。
以下是一个示例代码,演示了如何使用BeanUtils.copyProperties并处理源对象为null的情况:
```java
Category category = categoryMapper.selectById(category_id);
CategoryVo categoryVo = null;
if (category != null) {
categoryVo = new CategoryVo();
BeanUtils.copyProperties(category, categoryVo);
}
return categoryVo;
```
在上述代码中,首先通过categoryMapper查询得到一个Category对象。然后,判断该对象是否为null。如果不为null,则创建一个CategoryVo对象,并使用BeanUtils.copyProperties方法将Category对象的属性拷贝到CategoryVo对象中。最后,返回CategoryVo对象。