Spring 的 BeanUtils.copyProperties()实现的是浅拷贝
ClassA
public class ClassA {
private Integer age;
private String name;
private ClassC c;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ClassC getC() {
return c;
}
public void setC(ClassC c) {
this.c = c;
}
@Override
public String toString() {
return "ClassA{" +
"age=" + age +
", name='" + name + '\'' +
", c=" + c +
'}';
}
}
ClassB
public class ClassB {
private Integer age;
private String name;
private String other;
private ClassC d;
private ClassD c;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOther() {
return other;
}
public void setOther(String other) {
this.other = other;
}
public ClassD getC() {
return c;
}
public void setC(ClassD c) {
this.c = c;
}
public ClassC getD() {
return d;
}
public void setD(ClassC d) {
this.d = d;
}
@Override
public String toString() {
return "ClassB{" +
"age=" + age +
", name='" + name + '\'' +
", other='" + other + '\'' +
", c=" + c +
", d=" + d +
'}';
}
}
ClassC
public class ClassC {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "ClassC{" +
"name='" + name + '\'' +
'}';
}
}
ClassD
public class ClassD {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "ClassD{" +
"name='" + name + '\'' +
'}';
}
}
main
public static void main(String[] args) {
ClassA a=new ClassA();
a.setAge(10);
a.setName("A");
ClassC c=new ClassC();
c.setName("C");
a.setC(c);
ClassB b=new ClassB();
b.setAge(111);
b.setName("B");
ClassC c1=new ClassC();
c1.setName("C1");
b.setD(c1);
ClassD d=new ClassD();
d.setName("D");
b.setC(d);
System.out.println("我是改变前的a"+a);
System.out.println("我是改变前的b"+b);
System.out.println("我是改变前的c"+c);
BeanUtils.copyProperties(a,b);
System.out.println("我是改变后的a"+a);
System.out.println("我是改变后的b"+b);
System.out.println("我是改变后的c"+c);
}
结果
b只复制和a属性类型相同的值