前面写了一个序列化的文章,这次重新整理一下。

1.Serialize概念
Java的对象序列化就是将那些实现了Serializable接口的对象转换成一个字节序列。并能够
在以后将这个字节完全恢复为原来的对象。
对象序列化的概念加入到语言当中就是为了支持两种主要特性

一是Java的远程方法调用(Remote Method Invocation, RMI)。当向远程对象发送消息时,
需要通过序列化来传输参数和返回值。

二是Javabean对象序列化。有些服务器通过将所有的SESSION 数据(包括BEAN)写入磁盘来支持任意长的SESSION生命期,即使服务器停机也不会丢失。当服务器重新启动后,串行化的数据被恢复。同样的理由,在重负载的站点上支持服务器分簇的环境中,许多服务器通过串行化来复制SESSION。如果你的BEAN不支持串行化,服务器就不能正确地保存和传输类。

只要对象实现了Serializable接口,对象的序列化处理就会非常简单。
2.Serialize方法
要序列化一个对象,首先要创建某些OutputStream对象,然后将其封装在一个ObjectOutputStream对象内。
这时,只需要调用writeObject()即可将对象序列化,并将其发送给OutputStream。反之,将一个序列化对象还原为一个对象,需要将一个InputStream封装在ObjectInputStream内,然后调用readObject()。
OutputStream和InputStream常用的是ByteArrayOutputStream/FileOutputStream和ByteArrayInputStream/FileInputStream。

下面两个类以ByteArray方式实现序列化:

public final class Serialization
{

    /**
     * Serialize the object into a byte array.
     */
    public static byte[] serialize( Object obj )
        throws IOException
    {
        ByteArrayOutputStream  baos;
        ObjectOutputStream     oos;

        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream( baos );
        oos.writeObject( obj );
        oos.close();

        return baos.toByteArray();
    }


    /**
     * Deserialize an object from a byte array
     */
    public static Object deserialize( byte[] buf )
        throws ClassNotFoundException, IOException
    {
        ByteArrayInputStream  bais;
        ObjectInputStream     ois;

        bais = new ByteArrayInputStream( buf );
        ois = new ObjectInputStream( bais );
        return ois.readObject();
    }

}

public class DefaultSerializer
    implements Serializer
{

   
    public static final DefaultSerializer INSTANCE = new DefaultSerializer();
   
   
    /**
     * Construct a DefaultSerializer.
     */
    public DefaultSerializer()
    {
        // no op
    }

   
    /**
     * Serialize the content of an object into a byte array.
     *
     * @param obj Object to serialize
     * @return a byte array representing the object's state
     */
     public byte[] serialize( Object obj )
        throws IOException
     {
         return Serialization.serialize( obj );
     }
       
       
    /**
     * Deserialize the content of an object from a byte array.
     *
     * @param serialized Byte array representation of the object
     * @return deserialized object
     */
     public Object deserialize( byte[] serialized )
        throws IOException
     {
         try {
            return Serialization.deserialize( serialized );
         } catch ( ClassNotFoundException except ) {
            throw new WrappedRuntimeException( except );
         }
     }

}

File方式的序列化大致如下:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(out.txt));
out.writeObject(obj);
out.close();

ObjectInputStream in = new ObjectInputStream(new FileInputStream(out.txt));
Object obj = (Object)in.readObject();
in.close();

3.Serialize定制

缺省的序列化机制并不难操纵,如果有特殊的需求那又该怎么办?例如,也许要考虑特殊的安全问题,而且
你不希望对象的某一部分被序列化;或者一个对象被还原后,某子对象需要重新创建,从而不需要将该子对象
序列化。在这样的特殊情况下,可通过实现Externalizable接口来对序列化过程进行控制。这个Externalizable
接口继承了Serializable接口,同时增加了两个方法:writeExternal(ObjectOutput out)和readExternal(ObjectInput in)

Serializable对象完全以它存储的二进制位为基础来构造,而不用调用构造器。而对于一个Externalizable对象
缺省构造器都会被调用,然后调用readExternal()。下面列子中,如果Blip3()构造器注释掉,程序会报错:no valid constructor


// Reconstructing an externalizable object.
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
import com.bruceeckel.simpletest.*;
import java.io.*;
import java.util.*;

public class Blip3 implements Externalizable {
  private static Test monitor = new Test();
  private int i;
  private String s; // No initialization
  public Blip3() {
    System.out.println("Blip3 Constructor");
    // s, i not initialized
  }
  public Blip3(String x, int a) {
    System.out.println("Blip3(String x, int a)");
    s = x;
    i = a;
    // s & i initialized only in nondefault constructor.
  }
  public String toString() { return s + i; }
  public void writeExternal(ObjectOutput out)
  throws IOException {
    System.out.println("Blip3.writeExternal");
    // You must do this:
    out.writeObject(s);
    out.writeInt(i);
  }
  public void readExternal(ObjectInput in)
  throws IOException, ClassNotFoundException {
    System.out.println("Blip3.readExternal");
    // You must do this:
    s = (String)in.readObject();
    i = in.readInt();
  }
  public static void main(String[] args)
  throws IOException, ClassNotFoundException {
    System.out.println("Constructing objects:");
    Blip3 b3 = new Blip3("A String ", 47);
    System.out.println(b3);
    ObjectOutputStream o = new ObjectOutputStream(
      new FileOutputStream("Blip3.out"));
    System.out.println("Saving object:");
    o.writeObject(b3);
    o.close();
    // Now get it back:
    ObjectInputStream in = new ObjectInputStream(
      new FileInputStream("Blip3.out"));
    System.out.println("Recovering b3:");
    b3 = (Blip3)in.readObject();
    System.out.println(b3);
    monitor.expect(new String[] {
      "Constructing objects:",
      "Blip3(String x, int a)",
      "A String 47",
      "Saving object:",
      "Blip3.writeExternal",
      "Recovering b3:",
      "Blip3 Constructor",
      "Blip3.readExternal",
      "A String 47"
    });
  }
}