对象的深度克隆拷贝
当我们想要复制一个类的对象p1时,我们通常想到的方法是新建一个该类的对象p2,然后,挨个把p1的属性复制给p2。可是这样做会有一个问题:
如果该类有成员变量是其他类,我们经过这样的复制。能够给予p2的属性值只能是p1对应的对象的引用(换句话说p1和p2的某一属性指向的是一个对象,而不是两个相同的对象,这样会导致一个对象里面的属性变的话,这两个对象的属性都会相应的变化)。而java的对象输入输出流为我们提供了这种深度拷贝的实现方法。
1.测试类
import domain.Dog;
import domain.Person;
import util.FileUtil;
public class Test {
public static void main(String[] args) {
Dog pet = new Dog("acai");
Person p1 = new Person("小飞侠", pet);
System.out.println(p1.getPet());
System.out.println(p1.getPet().getName());
Person p2 = (Person)FileUtil.deeplyCopy(p1);
System.out.println(p2.getPet());
System.out.println(p2.getPet().getName());
}
}
2.工具类
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class FileUtil {
public static Object deeplyCopy(Serializable obj) {
try {
return bytes2object(object2bytes(obj));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static byte[] object2bytes(Serializable obj) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
baos.close();
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Object bytes2object(byte[] bytes) {
try {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
3.对象Person类
import java.io.Serializable;
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private Dog pet;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dog getPet() {
return pet;
}
public void setPet(Dog pet) {
this.pet = pet;
}
public Person(String name, Dog pet) {
super();
this.name = name;
this.pet = pet;
}
public Person() {
super();
}
}
4.对象Dog类
import java.io.Serializable;
public class Dog implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dog(String name) {
super();
this.name = name;
}
public Dog() {
super();
}
}