Java对象序列化

在Java中,实现对象序列化有两种方式:第一种是实现Serializable接口;第二种是实现Externalizable接口

其实,查看JDK源代码就会发现Externalizable也是继承自Serializable接口的,只不过在Externalizable中添加了两个抽象方法,具体如下:

public interface Externalizable extends java.io.Serializable {
    /**
     * The object implements the writeExternal method to save its contents
     * by calling the methods of DataOutput for its primitive values or
     * calling the writeObject method of ObjectOutput for objects, strings,
     * and arrays.
     *
     * @serialData Overriding methods should use this tag to describe
     *             the data layout of this Externalizable object.
     *             List the sequence of element types and, if possible,
     *             relate the element to a public/protected field and/or
     *             method of this Externalizable class.
     *
     * @param out the stream to write the object to
     * @exception IOException Includes any I/O exceptions that may occur
     */
    void writeExternal(ObjectOutput out) throws IOException;

    /**
     * The object implements the readExternal method to restore its
     * contents by calling the methods of DataInput for primitive
     * types and readObject for objects, strings and arrays.  The
     * readExternal method must read the values in the same sequence
     * and with the same types as were written by writeExternal.
     *
     * @param in the stream to read data from in order to restore the object
     * @exception IOException if I/O errors occur
     * @exception ClassNotFoundException If the class for an object being
     *              restored cannot be found.
     */
    void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;
}

 

下边看Java对象两种实现序列化的方式:

  • 实现Serializable接口
import java.io.Serializable;

public class SerializableObject implements Serializable {
	private static final long serialVersionUID = -1078175389486772845L;
	……
}
  • 实现Externalizable接口
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class ExternalizableObject implements Externalizable {

	@Override
	public void readExternal(ObjectInput arg0) throws IOException,
			ClassNotFoundException {
		// TODO Auto-generated method stub

	}

	@Override
	public void writeExternal(ObjectOutput arg0) throws IOException {
		// TODO Auto-generated method stub

	}

}

 这两种方式最大的不同在于实现Externalizable接口的这种方式需要开发者自己去实现序列化的过程,即重写readExternal和writeExternal这两个方法。

你可能感兴趣的:(java对象序列化)