BeanUtil.copyProperties指定属性
时间: 2023-10-17 09:26:42 浏览: 144
BeanUtil.copyProperties方法是一个常用的工具类方法,用于将一个Java对象的属性值复制到另一个Java对象中。该方法提供了两种常用的用法。
第一种用法是复制所有属性,不包括null值属性。使用该用法时,可以直接调用BeanUtil.copyProperties(source, target)方法,将源对象的属性值复制到目标对象中。
第二种用法是复制指定的属性。使用该用法时,需要自定义一个属性过滤器,并在调用BeanUtil.copyProperties(source, target, propertyFilter)方法时传入该过滤器。属性过滤器需要实现PropertyFilter接口,并重写其apply方法,在apply方法中判断哪些属性需要复制。
下面是一个示例代码:
```java
public class CopyPropertiesExample {
public static void main(String[] args) {
SourceObject source = new SourceObject();
source.setName("John");
source.setAge(25);
source.setEmail("[email protected]");
TargetObject target = new TargetObject();
BeanUtil.copyProperties(source, target, (sourceValue, targetValue, property) -> {
// 只复制age和email属性
return "age".equals(property) || "email".equals(property);
});
System.out.println(target.getName()); // 输出null
System.out.println(target.getAge()); // 输出25
System.out.println(target.getEmail()); // 输出"[email protected]"
}
}
class SourceObject {
private String name;
private int age;
private String email;
// 省略getter和setter方法
}
class TargetObject {
private String name;
private int age;
private String email;
// 省略getter和setter方法
}
```
在上面的示例中,只复制了源对象的age和email属性到目标对象中,name属性没有被复制。
阅读全文
相关推荐

















