这周项目写创建内容接口时出现一个问题,我输出的数据怎么都变了?
过程是这样的,有一个接口可查到目前所有数据,返回的那叫一个全,然后我就调用后复制呗,那不能一个一个复制吧,就调用了BeanUtils.copyProperties()
.我以为这就万事大吉了,然后就测试呗,结果却和我想要的不一样,我就想这咋回事,排查后发现问题出在了我的对象身上,因为我的实例对象里有引用类型的,后来我给他改了,就出现问题了。
我来给大家验证一下过程:
Student类
public class Student {
private String name;
private Integer age;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Teacher类,里边有一个Student引用类型
public class Teacher {
private String tName;
private Integer tAge;
private Student student;
@Override
public String toString() {
return "Teacher{" +
"tName='" + tName + '\'' +
", tAge=" + tAge +
", student=" + student +
'}';
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public String gettName() {
return tName;
}
public void settName(String tName) {
this.tName = tName;
}
public Integer gettAge() {
return tAge;
}
public void settAge(Integer tAge) {
this.tAge = tAge;
}
}
客户端类
import org.springframework.beans.BeanUtils;
public class Client {
public static void main(String[] args) {
Teacher teacher = new Teacher();
Teacher teacher1 = new Teacher();
Student student = new Student();
teacher.settName("老师");
teacher.settAge(23);
teacher.setStudent(student);
student.setAge(10);
student.setName("赵高");
System.out.println(teacher.toString());
System.out.println(teacher1.toString());
System.err.println("==================================");
BeanUtils.copyProperties(teacher, teacher1);
System.out.println(teacher.toString());
System.out.println(teacher1.toString());
System.err.println("==================================");
teacher1.getStudent().setName("王麻子");
System.out.println("深复制or浅复制" + teacher.toString());
System.out.println("深复制or浅复制" + teacher1.toString());
}
}
输出如下:
Teacher{tName='老师', tAge=23, student=Student{name='赵高', age='10'}}
Teacher{tName='null', tAge=null, student=null}
==================================
Teacher{tName='老师', tAge=23, student=Student{name='赵高', age='10'}}
Teacher{tName='老师', tAge=23, student=Student{name='赵高', age='10'}}
==================================
深复制or浅复制Teacher{tName='老师', tAge=23, student=Student{name='王麻子', age='10'}}
深复制or浅复制Teacher{tName='老师', tAge=23, student=Student{name='王麻子', age='10'}}
引用改了,那么之前那个示例对象的引用也改了,所以这是浅复制,做个笔记,以后要谨记