第一种方案实现
worker
package com.geekmice.springbootaop.clone;
public class Worker implements Cloneable {
private String name;
private String gender;
private Integer age;
private EducationInfo educationInfo;
public Worker(String name, String gender, Integer age,String school,String time) {
this.name = name;
this.gender = gender;
this.age = age;
this.educationInfo=new EducationInfo(school,time);
}
@Override
protected Object clone() throws CloneNotSupportedException {
Worker worker = new Worker(name, gender,age, educationInfo.getSchool(), educationInfo.getTime());
return worker;
}
public EducationInfo getEducationInfo() {
return educationInfo;
}
public void setEducationInfo(EducationInfo educationInfo) {
this.educationInfo = educationInfo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
EducationInfo
package com.geekmice.springbootaop.clone;
public class EducationInfo implements Cloneable {
private String school;
private String time;
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public EducationInfo(String school, String time) {
this.school = school;
this.time = time;
}
}
client
package com.geekmice.springbootaop.clone;
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
Worker worker = new Worker("罗士信", "男", 18, "北京大学", "2022-10-09");
System.out.println("原始对象:"+worker.getEducationInfo().getSchool());
Worker cloneWorker =(Worker) worker.clone();
System.out.println("第一种方案深拷贝"+cloneWorker.getEducationInfo().getSchool());
cloneWorker.getEducationInfo().setSchool("清华大学");
System.out.println("变化原始对象:"+worker.getEducationInfo().getSchool());
System.out.println("变化第一种方案深拷贝:"+cloneWorker.getEducationInfo().getSchool());
}
}
原始对象:北京大学
第一种方案深拷贝北京大学
变化原始对象:北京大学
变化第一种方案深拷贝:清华大学
第二种方案实现
核心代码Worker,其他代码不变
@Override
protected object clone throws CloneNotSupportedException{
Worker worker = (Worker) super.clone();
worker.education=(EducationInfo)educationInfo.clone();
return worker;
}
第三种方案
需要实现序列化接口Serializeable
重写clone方法,通过流方式
@Override
protected object clone() throws CloneNotSupportedException{
Worker worker = null;
try{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream();
oos.writeObject(this);
// 流序列化对象
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream();
worker = (Worker)ois.readObject();
} catch(IOException | ClassNotFoundException e){
e.printStackTrace();
}
return worker;
}