首页 > 代码库 > Serializable与transient的联合使用:动态管理成员属性——《Thinking in Java》随笔033

Serializable与transient的联合使用:动态管理成员属性——《Thinking in Java》随笔033

 1 //: SerialCtl.java
 2 // 下面这个Demo演示如何使用Serializable和transient关键字来动态管理成员属性
 3 // 主要思想是添加(不是复写与实现)write与read的方法(注意方法签名)
 4 
 5 package c10;
 6 
 7 import java.io.ByteArrayInputStream;
 8 import java.io.ByteArrayOutputStream;
 9 import java.io.IOException;
10 import java.io.ObjectInputStream;
11 import java.io.ObjectOutputStream;
12 import java.io.Serializable;
13 
14 /**
15 *    @time:         上午10:01:53
16 *    @date:         2017年5月11日
17 *    @auther:    skyfffire
18 *    @version:    v0.1
19 */
20 public class SerialCtl implements Serializable {
21     private static final long serialVersionUID = -7532371062424412783L;
22 
23     String a = null;
24     transient String b = null;
25     
26     public SerialCtl(String aa, String bb) {
27         a = "Not Transient: " + aa;
28         b = "Transient: " + bb;
29     }
30     
31     public String toString() {
32         return a + "\n" + b;
33     }
34     
35     private void writeObject(ObjectOutputStream stream) 
36             throws IOException {
37         stream.defaultWriteObject();
38         stream.writeObject(b);
39     }
40     
41     private void readObject(ObjectInputStream stream) 
42             throws IOException, ClassNotFoundException {
43         stream.defaultReadObject();
44         b = (String) stream.readObject();
45     }
46     
47     public static void main(String[] args) {
48         SerialCtl sc = new SerialCtl("Test1", "Test2");
49         
50         System.out.println("Before:\n" + sc);
51         
52         ByteArrayOutputStream buf = 
53                 new ByteArrayOutputStream();
54 
55         try {
56             ObjectOutputStream o = new ObjectOutputStream(buf);
57             o.writeObject(sc);
58             o.close();
59             
60             ObjectInputStream in = 
61                     new ObjectInputStream(
62                             new ByteArrayInputStream(buf.toByteArray()));
63             sc = (SerialCtl) in.readObject();
64             in.close();
65             System.out.println(sc);
66         } catch (Exception e) {
67             e.printStackTrace();
68         }
69     }
70 }
71 
72 ///:~

 

Serializable与transient的联合使用:动态管理成员属性——《Thinking in Java》随笔033