clone一个对象
第一步:
让此对象实现Cloneable类,然后重写clone()方法。
原本clone()方法为受保护的,我们改为public之后即可调用。
/**
* @Author jiajun.xiong
* @Date 2021/6/6 17:33
* @Version 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Cloneable {
private String id;
private String name;
private String age;
private String stuNumber;
//重写clone方法,将默认的protected改为public
@Override
public Student clone() throws CloneNotSupportedException {
return (Student) super.clone();
}
}
第二步
调用clone方法,通过打印的结果发现这里修改克隆后的对象属性时源对象的属性值不会发生改变,与预期相符克隆成功。
@Test
void test2() {
try {
Student student = new Student("sId","sName","sAge","sNumber");
Student student1 = student.clone();
student1.setName("克隆Student");
System.out.println(student);
System.out.println(student1);
}catch (Exception e){
System.out.println("clone失败");
}
}
注意
在这种情况下,我们可能会碰到此对象中还有其他对象的例子
package com.yida.qinyitem.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author jiajun.xiong
* @Date 2021/6/6 17:54
* @Version 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Worker{
private String id;
private String name;
private String age;
private Student student;
}
这时候如果我们还是按照上面的步骤只操作Worker类实现Cloneable重写clone方法会出现问题,更改克隆的Worker对象的Student属性时源Worker的Student属性也会一同改变。
所以我们在这种情况下,
需要先操作Worker类实现Cloneable重写clone方法在方法中对Worker类中的Student进行克隆,同时也操作Student类实现Cloneable并实现clone方法。
代码如下:
package com.yida.qinyitem.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author jiajun.xiong
* @Date 2021/6/6 17:54
* @Version 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Worker implements Cloneable{
private String id;
private String name;
private String age;
private Student student;
@Override
public Worker clone() throws CloneNotSupportedException {
Worker clone = (Worker) super.clone();
clone.student = student.clone();
return clone;
}
}
package com.yida.qinyitem.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author jiajun.xiong
* @Date 2021/6/6 17:33
* @Version 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Cloneable {
private String id;
private String name;
private String age;
private String stuNumber;
@Override
public Student clone() throws CloneNotSupportedException {
return (Student) super.clone();
}
}
测试
@Test
void contextLoads() {
Worker worker = new Worker("id","name","age",new Student("sId","sName","sAge","sNumber"));
try {
Worker worker1 = worker.clone();
worker1.getStudent().setId("sID1");
worker1.setId("id1");
System.out.println(worker);
System.out.println(worker1);
}catch (Exception e){
System.out.println("clone失败");
}
}
测试发现经过上述的操作不管更改克隆后的Worker基本属性还是引用属性都不会改变源对象的值。完毕!