JAVA序列化Serializable

大家都知道Serializable是一个mark interface,告诉JVM这个对象可以被转换成二进制流来传输.
但是Serializable与Externalizable的转换二进制流的过程是不一样的.
Serializable 在我们实现这个接口的时候,我们可以使用4个私有方法来控制序列化的过程:
我们来看一个例子:

代码
  1.    public class FooImpl implements java.io.Serializable{   
  2. private String message;   
  3.   
  4. public String getFoo() {           
  5.     return message;   
  6. }   
  7.   
  8. public void setMessage(String message) {   
  9.     this.message = message;   
  10. }   
  11.   
  12. private void writeObject(java.io.ObjectOutputStream out) throws IOException {   
  13.     System.out.println("writeObject invoked");   
  14.     out.writeObject(this.message == null ? "hohohahaha" : this.message);   
  15. }   
  16.   
  17. private void readObject(java.io.ObjectInputStream in) throws IOException,   
  18.         ClassNotFoundException {   
  19.     System.out.println("readObject invoked");   
  20.     this.message = (String) in.readObject();   
  21.     System.out.println("got message:" + message);   
  22. }   
  23.   
  24. private Object writeReplace() throws ObjectStreamException {   
  25.     System.out.println("writeReplace invoked");   
  26.     return this;   
  27. }   
  28.   
  29. private Object readResolve() throws ObjectStreamException {   
  30.     System.out.println("readResolve invoked");   
  31.     return this;   
  32. }   
  33.   
  34. public Object serialize() throws IOException, ClassNotFoundException {   
  35.     ByteArrayOutputStream baos = new ByteArrayOutputStream();   
  36.     ObjectOutputStream oos = new ObjectOutputStream(baos);   
  37.     oos.writeObject(this);   
  38.     ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());   
  39.     ObjectInputStream ois = new ObjectInputStream(bais);   
  40.     return ois.readObject();   
  41. }   
  42.         public static void main(String[] args) throws IOException,    
  43.              ClassNotFoundException {   
  44.                  FooImpl fooimpl = new FooImpl();   
  45.                  fooimpl.serialize();   
  46. }   
  47.   
<script type="text/javascript">render_code();</script>
我们运行这段代码看到的debug信息:
writeReplace invoked
writeObject invoked
readObject invoked
readResolve invoked

 

当进行序列化的时候:
首先JVM会先调用writeReplace方法,在这个阶段,我们可以进行张冠李戴,将需要进行序列化的对象换成我们指定的对象.
跟着JVM将调用writeObject方法,来将对象中的属性一个个进行序列化,我们可以在这个方法中控制住哪些属性需要序列化.

当反序列化的时候:
JVM会调用readObject方法,将我们刚刚在writeObject方法序列化好的属性,反序列化回来.
然后在readResolve方法中,我们也可以指定JVM返回我们特定的对象(不是刚刚序列化回来的对象).

注意到在writeReplace和readResolve,我们可以严格控制singleton的对象,在同一个JVM中完完全全只有唯一的对象,控制不让singleton对象产生副本.


 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值