BeanUtils.copyProperties 空值也会被复制过去
时间: 2024-05-10 21:12:55 浏览: 16
BeanUtils.copyProperties 是一个 Apache Commons BeanUtils 库提供的工具类,可以将一个 JavaBean 对象的属性值复制到另一个 JavaBean 对象中。当源对象和目标对象具有相同名称和类型的属性时,该方法会将源对象的属性值复制到目标对象中。
对于空值,如果源对象的属性值为 null,则目标对象的相应属性值也将设置为 null。如果您需要自定义 BeanUtils.copyProperties 的行为,例如忽略某些属性或者处理空值,可以使用 BeanUtilsBean 类和 ConvertUtilsBean 类来实现。
相关问题
BeanUtils.copyProperties排除空值属性
BeanUtils.copyProperties方法是Apache Commons BeanUtils库中的一个工具方法,用于将一个Java对象的属性值复制到另一个Java对象中。默认情况下,该方法会将源对象的所有属性值复制到目标对象中,包括空值属性。
如果你想要排除空值属性,可以使用自定义的属性拷贝器(PropertyUtilsBean)来实现。以下是一种可能的实现方式:
1. 创建一个自定义的属性拷贝器类,继承自PropertyUtilsBean类,并重写copyProperties方法。
```java
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.DynaBean;
public class CustomPropertyUtils extends PropertyUtilsBean {
@Override
public void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(orig);
for (PropertyDescriptor origDescriptor : origDescriptors) {
String name = origDescriptor.getName();
if (PropertyUtils.isReadable(orig, name) && PropertyUtils.isWriteable(dest, name)) {
Object value = PropertyUtils.getSimpleProperty(orig, name);
if (value != null) {
PropertyUtils.setSimpleProperty(dest, name, value);
}
}
}
}
}
```
2. 在你的代码中使用自定义的属性拷贝器类进行属性拷贝。
```java
CustomPropertyUtils customPropertyUtils = new CustomPropertyUtils();
customPropertyUtils.copyProperties(destObject, sourceObject);
```
这样,只有源对象中非空的属性值才会被复制到目标对象中。
BeanUtils.copyProperties 拷贝空值么
BeanUtils.copyProperties 方法默认情况下会拷贝源对象中的所有属性值到目标对象中,包括空值(null)。如果源对象的属性值为 null,那么目标对象的对应属性值也会被设置为 null。如果需要在拷贝时忽略空值,可以使用 BeanUtils.copyProperties 方法的另一个重载方法,该方法接受一个 PropertyDescriptor 数组参数用于指定需要忽略的属性。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)