需求
需求,把一个对象复制一份新的,实现深拷贝,也就是说新旧对象的属性改变完全互不影响。
实现
原理就是将这个Object实现Serializable接口,并实现deepClone方法,在deepClone方法里,对这个对象进行序列化和反序列化的操作,那么新对象肯定就是实现了深拷贝了,代码如下:
Student.java
public class Student implements Serializable { private int age; private String name; public Student(String name, int age) { this.name = name; this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } protected Student deepClone() throws Exception { //序列化 ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); //反序列化 ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return (Student) ois.readObject(); } }
测试代码:
public class Test1 { public static void main(String[] args) throws Exception { Student student1 = new Student("Terry", 18); Student student2 = student1; //普通的clone or student1.clone(); Student student3 = student1.deepClone(); // 深拷贝 student1.setName("Tom"); System.out.println(student2.getName());//把student1修改成了Tom,student2也变成了Tom System.out.println(student3.getName());//deepClone后,student3不会随着student1而改变了 } }
文章评论