package com.test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class StudentClone implements Cloneable,Serializable
{
static final long serialVersionUID = -8084210473720589252L;
String name;
int age;
List<String> list = new ArrayList<String>(){{
add("A");
add("B");
add("C");
}};
StudentClone(String name,int age)
{
this.name=name;
this.age=age;
}
public Object clone(){
try{
//save the object to a byte array
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(this);
out.close();
//read a clone of the object from byte array
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(bin);
Object ret = in.readObject();
in.close();
return ret;
}catch(Exception e){
return null;
}
}
public static void main(String[] args)
{
StudentClone s1= new StudentClone("zhangsan",50);
StudentClone s2=(StudentClone)s1.clone();
s2.list.add("D");
s2.name="lisi";
s2.age=20;
System.out.println("name="+s1.name+","+"age="+s1.age);//修改学生2后,不影响学生1的值。
System.out.println("name="+s2.name+","+"age="+s2.age);
System.out.println("name="+s1.name+","+"age="+s1.age);
System.out.println(s1.list.size()+"hhhhhhh");
System.out.println(s2.list.size()+"uuuuuuu");
}
}
java 序列化实现深度克隆
最新推荐文章于 2025-06-21 11:07:22 发布