将给定源bean的属性值复制到目标bean中
原理
copyProperties使用了jdk自带的自省机制。 自省 简单来说就是jdk在 反射 上又做了一层包装,针对于Bean对象的属性读写。
遍历target对象的属性,获取target对象属性的write方法,根据target对象的属性名,获取source对象的属性
如果有同样名字的属性,调用source对象属性的read方法得到值,调用target对象属性的write方法,给属性赋值
使用实例
public class vipTwo {
private String name;
private String sex;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "vipTwo{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
vip 实体
public class vipTwo {
private String name;
private String sex;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "vipTwo{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
vipTwo 实体
public class vipTwo {
private String name;
private String sex;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "vipTwo{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
// 将给定源bean的属性值复制到目标bean中
public static void copyProperties(Object source, Object target)
// 仅设置给定“可编辑”类(或接口)中定义的属性
public static void copyProperties(Object source, Object target, Class> editable)
// 忽略的属性名称数组
public static void copyProperties(Object source, Object target, String... ignoreProperties)
// 仅设置给定“可编辑”类(或接口)中定义的属性 and 忽略的属性名称数组
private static void copyProperties(Object source, Object target, @Nullable Class> editable,
@Nullable String... ignoreProperties)
将给定源bean的属性值复制到目标bean中 (忽略name 属性)
http://www.flammulina.com/2018/09/23/beanutils-copyproperties/