09
10 class House implements Serializable{
11 private static final long serialVersionUID = 7726379233155420025L;
12 }
13
14 class Animal implements Serializable{
15 private static final long serialVersionUID = 8278386775550453403L;
16 private String name;
17 private House house;
18
19 public Animal(String name,House house){
20 this.name = name;
21 this.house = house;
22 }
23 public String toString(){
24 return name + "[" + super.getClass() + "], " + house +"\n";
25 }
26 }
27 @SuppressWarnings("unchecked")
28 public class MyWorld {
29 public static void main(String[] args) {
30 House house = new House();
31
32 Vector animals = new Vector();
33 animals.add(new Animal("dog", house));
34 animals.add(new Animal("cat", house));
35 animals.add(new Animal("mouse", house));
36 System.out.println(animals);
37 try{
38 ByteArrayOutputStream buf1 = new ByteArrayOutputStream();
39 ObjectOutputStream out1 = new ObjectOutputStream(buf1);
40 out1.writeObject(animals);
41 out1.writeObject(animals);
42 ByteArrayOutputStream buf2 = new ByteArrayOutputStream();
43 ObjectOutputStream out2 = new ObjectOutputStream(buf2);
44 out2.writeObject(animals);
45 out1.close();
46 out2.close();
47
48 ObjectInputStream in1 = new ObjectInputStream(new ByteArrayInputStream(buf1.toByteArray()));
49 ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(buf2.toByteArray()));
50 Vector animal1 = (Vector)in1.readObject();
51 Vector animal2 = (Vector)in1.readObject();
52 Vector animal3 = (Vector)in2.readObject();
53 /**
54 * 1.animal1和animal2是同一个数据流中的对象,animal3是另一个数据流的对象,当对象的被恢复的时候可以看到
55 * house地址的区别:animal1和animal2中是相同的,而他们跟animal3是不同的,所以在同一个数据流中,相同的
56 * 对象不会重复出现。
57 * 2.当数据流不同的时候,所生成的对象网也会不同
58 */
59 System.out.println(animal1);
60 System.out.println(animal2);
61 System.out.println(animal3);
62
63 System.out.println(animals);
64 }catch(Exception e){
65 e.printStackTrace();
66 }
67 }
68 }
只要将对象序列化到单独一个数据流里面,就能恢复获得与以前一样的对象网,不会不慎造成对象的重复。要想保存系统状态,最安全的方法是将构成系统状态的所有对象都置入单个集合内,并在一次操作力完成那个集合的写入,这样就只需一次方法调用便可恢复。
这是我在序列化学习中学到的一些知识,若有不正确之处,望大家斧正,小菜拜谢。
------>froest
扬帆起航,生命正式从这里开始...
爱情终将消失于茫茫的时间洪流之中,沉淀于厚重的黄泥沙丘之下...