浅拷贝
被拷贝对象的所有变量都含有与原来的对象相同的值,如果改被拷贝的对象或者原对象,那么两个对象的值都会修改。下面代码中,改变student1或者student2 ,两个对象的值就都改变了。
public static void main(String[] args) throws Exception {
Student student1 = new Student("小明",12);
Student student2 = student1;
student1.setAge(11);
//student1 和student2 都改变了
System.out.println(student1+"-----"+student2);
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Student {
private String name;
private Integer age;
}
深拷贝
深拷贝后的对象与原来的对象是完全隔离的,互不影响,对一个对象的修改并不会影响另一个对象。项目中,我们常用的就是深拷贝,就是改一个对象,另一个对象不做修改。
深拷贝工具类
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Slf4j
public class BeanConvertUtil {
/**
* 对象拷贝
*
* @param <T> the type parameter
* @param srcObj the src obj
* @param destClass the dest class
*
* @return the t
*/
public static <T> T convert(Object srcObj, Class<T> destClass) {
if (Objects.isNull(srcObj)) {
return null;
}
String srcJson = "";
if (srcObj instanceof String) {
srcJson = (String) srcObj;
} else {
srcJson = JSON.toJSONString(srcObj);
}
return JSON.parseObject(srcJson, destClass);
}
/**
* 对象List拷贝
*
* @param <T> the type parameter
* @param srcObjList the src obj list
* @param destClass the dest class
*
* @return the list
*/
public static <T> List<T> transformBeanList(List<?> srcObjList, Class<T> destClass) {
List<T> destList = new ArrayList<>();
if (!CollectionUtils.isEmpty(srcObjList)) {
destList = JSON.parseArray(JSON.toJSONString(srcObjList), destClass);
}
return destList;
}
}
深拷贝工具类使用
下面代码中,改变student1对象,student2则不会改变 ,两个对象的值起到了隔离作用。
public static void main(String[] args) throws Exception {
Student student1 = new Student("小明",12);
Student student2 = BeanConvertUtil.convert(student1, Student.class);
student1.setAge(11);
System.out.println(student1+"----"+student2);
/**
* 拷贝List对象
*/
Student student3 = new Student("小明",12);
Student student4 = new Student("小明",12);
List<Student> studentList1 = new ArrayList<>();
studentList1.add(student3);
studentList1.add(student4);
List<Student> studentList2 = BeanConvertUtil.transformBeanList(studentList1, Student.class);
}