项目中一般传输类,实体类,视图类等等对象,它们之间需要来回转换,对象的属性大部分重合,如果一个一个属性set的话就会有有许多看起来比较难受的代码。这里我们就用到了对象直接内容的拷贝了。把一个对象的内容拷贝到另外一个对象,根据属性名一样拷贝。
浅拷贝:拷贝对象里面的属性--》另外一个对象的属性
深拷贝:对象里面还会嵌套对象,对象里面还有属性,浅拷贝无法完成对象里面对象的拷贝。
使用 BeanUtils.copyProperties(),这个方法,spring和apache都有这个方法,推荐使用spring的
基本用法(详细看博客:http://www.cnblogs.com/dongfangshenhua/p/7099970.html)
1.把a拷贝到b,注意两个方法的拷贝对象位置
2.要求两个Bean的属性名相同,且有对应的setXxx方法和getXxx方法。
3.基本类型与其对应的封装类型可以相互转换 注意类型转换的问题 :https://blog.csdn.net/cyuanxin/article/details/82780447
1.spring的BeanUtils.copyProperties(a,b)
把前面的对象,拷贝到后面位置去
引入的包:package org.springframework.beans
2.apache的BeanUtils.copyProperties(b,a)
把后面的对象,拷贝到前面位置去
引入的包:package org.apache.commons.beanutils;
这是一种列表情况下的,需要在新类中加上构造函数,看例子吧。
主要是这一句:teacher.stream().map(TeacherVO::new).collect(Collectors.toList())
测试转换的类
import model.Student;
import model.StudentVO;
import model.Teacher;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author : null
* @date : 2019/1/5
* @description:
*/
public class DeepCopy {
public static void main(String[] args) {
Student student = new Student();
student.setNumber(1);
List list = new ArrayList<>();
Teacher teacher = new Teacher("我是老师");
student.setTeacher(teacher);
list.add(student);
List studentVOS = list.stream().map(StudentVO::new).collect(Collectors.toList());
for (StudentVO studentVO : studentVOS) {
System.out.println(studentVO.getNumber());
System.out.println(studentVO.getTeacher().getTeahcerName());
}
}
}
输出结果:顺利在新类中取出来这些内容
1
我是老师
附上另外三个实体
/**
* @author : null
* @date : 2018/11/20
* @description:
*/
public class Student{
private String name;
private Integer number;
private Teacher teacher;
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
}
/**
* @author : null
* @date : 2019/1/5
* @description:
*/
public class StudentVO {
private String name;
private Integer number;
private Teacher teacher;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public StudentVO(Student student) {
this.name = student.getName();
this.number = student.getNumber();
if (null != student.getTeacher()) {
this.teacher = student.getTeacher();
}
}
}
**
* @author : null
* @date : 2019/1/5
* @description:
*/
public class Teacher {
private String teahcerName;
public String getTeahcerName() {
return teahcerName;
}
public void setTeahcerName(String teahcerName) {
this.teahcerName = teahcerName;
}
public Teacher(String teahcerName) {
this.teahcerName = teahcerName;
}
}