public class Test {
public static void main(String[] args) {
People p1 = new People("happy",1);
try {
ByteArrayOutputStream bas =new ByteArrayOutputStream();//字节
ObjectOutputStream oos = new ObjectOutputStream(bas);//对象
oos.writeObject(p1);//写对象
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bas.toByteArray()));//对象输入流,序列化
People p2 =(People) ois.readObject();//读对象输入流,反序列化
bas.flush();oos.flush();
bas.close();oos.close();
ois.close();
System.out.println(p1);
System.out.println(p2);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class People implements Serializable{//必须实现Serializable接口
private String name;
private int age;
public People2(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
序列化和反序列化实现深度克隆
最新推荐文章于 2020-12-23 15:19:12 发布