刚才那个程序是潜克隆,这个是我用序列化方式实现的深克隆
import java.io.ByteArrayInputStream;
/**
*
* 程序说明,本例子通过序列化实现深克隆
*
* @author Administrator
*
*/
public class SerialazableTest2 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Student s1=new Student("jack",10);
s1.setDog(new Dog("阿笨"));
Student s2=(Student)s1.deepCopy();
s1.setDog(new Dog("阿扁"));//这里已经实现了深克隆了所以s1的改变不会影响到s2的引用
System.out.println(s2.getDog().getName());
}
}
class Student implements Serializable{
private String name;
private int age;
private Dog dog;
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
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;
}
public Student (){}
public Student(String name,int age){
this.name=name;
this.age=age;
}
public Object deepCopy() throws IOException, ClassNotFoundException{
//使用FileOutputStream这个节点流是一定要写入文件的,这里写入文件也没有多大用处,所以适用ByteArrayOutputStream
File file=new File("text.txt");
FileOutputStream fos=new FileOutputStream(file);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(this);
FileInputStream fis=new FileInputStream(file);
ObjectInputStream ois=new ObjectInputStream(fis);
Object obj=ois.readObject();
ois.close();
//这里使用ByteArrayOutputStream更好,因为这样就不用写到文件中了,只是写到内存中,不用创建文件了
// ByteArrayOutputStream baos=new ByteArrayOutputStream();
// ObjectOutputStream oos=new ObjectOutputStream(baos);
// oos.writeObject(this);
// ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
// ObjectInputStream ois=new ObjectInputStream(bais);
// Object obj=ois.readObject();
// ois.close();
//
return obj;
}
}
class Dog implements Serializable{//被包含的引用对象也要实现可序列化接口,如果不想被序列化用transient标示
private String name;//transient如果这里用transient标示了,那么就表示不能被序列化了,将显示null
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dog(String name){
this.name=name;
}
} |