通过实现Serializable接口,可以让一个类的拥有序列化和反序列化的能力。可序列化类的所有子类,都可以序列化。这个接口没有任何的方法定义,它仅仅只是标记某个类能被序列化和反序列化。
想让一个非序列化类的子类拥有序列化能力,这个子类在反序列化的时候,需要恢复父类的public、protected以及其它可以访问的字段,子类通过调用父类的无参构造方法,在反序列化的时候,恢复父类(可访问)字段。如果不是这样,子类将无法实现序列化(这种错误将会在运行时阶段被jvm发现)。子类自己的字段,则通过存储在序列化流中的数据来恢复值。
类在序列化和反序列化过程中,如果需要做一些特殊处理,则需要实现下列的方法:
private void writeObject(java.io.ObjectOutputStream out) throws IOException
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;
private void readObjectNoData() throws ObjectStreamException;
writeObject方法负责将对象的字段的值写入序列化流中,而对应readObject方法则负责恢复对象字段的值。可以通过调用out.defaultWriteObject方法来使用默认的序列化机制。这个方法不需要关注父类或子类的字段。writeObject方法将字段的值写入到ObjectOutputStream流中,来达到保存的目的。对于原始数据类型的字段,则通过DataOutput提供的方法来实现保存。
readObject方法负责从流中读取数据,然后按照字段名称恢复对象的字段值。可以通过调用in.defaultReadObject方法来启用默认的反序列化机制:恢复非static和非transient字段。readObject方法不需要关注父类或子类的字段。
当出现反序列化与序列化类的版本不一致的情况时,readObjectNoData方法负责初始化对象的字段值。这种情况可能发生在:反序列化时,接收方使用了发送方对象的类的不同版本,或者接收方继承的类的版本与发送方继承的类的版本不一致。另外,当序列化流被篡改了,也会发生这种情况。因此,当出现类不一致或者反序列化流不完全的情况时,readObjectNoData初始化反序列化对象的字段就非常有用。
在将对象写入序列化流时,如果替换成另一个对象写入流,则需要重写如下方法:
ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException;
如果writeReplace方法存在,而且它能够被对象的其它成员方法访问,则它会被序列化机制调用。因此,这个方法可以是private, protected和package-private。
反序列化时,如果需要替换成另一个对象,则需要重写如下方法:
ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;
readResolve的调用方式及可访问特性与writeReplace一样。
序列化机制会给每个能被序列化的类关联一个数字类型的版本号,版本号的名字是:serialVersionUID,这个版本号,用于在反序列化时,检测发送方和接收方所使用的对象的类是否一致。如果接收方加载的类与发送方加载的类的serialVersionUID不一致,则反序列化时会抛出InvalidClassException异常。一个可序列化类可以通过明确的定义一个long类型的,使用static和final修饰的”serialVersionUID”字段,来指定它的版本号。如下所示:
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
如果一个可序列化类没有明确的定义一个serialVersionUID字段,则序列化运行时会为类计算出一个默认的serialVersionUID值。但是强烈建议为每个可序列化的类明确的定义serialVersionUID,因为默认的serialVersionUID值过多依赖类的细节和编译环境,很容易导致反序列化过程中抛出InvalidClassException异常。因此,想要让序列化和反序列化兼容各种不同的编译环境,就需要为类定义一个serialVersionUID字段。由于serialVersionUID只是标记当前类本身的版本,不适用于继承机制,因此,强烈建议将serialVersionUID字段定义成private的。无法为数组对象(如int[], Integer[], Object[]等)定义serialVersionUID,因此它们使用默认的版本号,但是数组对象反序列化过程中对比serialVersionUID的机制已经被废弃了。
Serializable源码如下:
/*
* %W% %E%
*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.io;
/**
* Serializability of a class is enabled by the class implementing the
* java.io.Serializable interface. Classes that do not implement this
* interface will not have any of their state serialized or
* deserialized. All subtypes of a serializable class are themselves
* serializable. The serialization interface has no methods or fields
* and serves only to identify the semantics of being serializable. <p>
*
* To allow subtypes of non-serializable classes to be serialized, the
* subtype may assume responsibility for saving and restoring the
* state of the supertype's public, protected, and (if accessible)
* package fields. The subtype may assume this responsibility only if
* the class it extends has an accessible no-arg constructor to
* initialize the class's state. It is an error to declare a class
* Serializable if this is not the case. The error will be detected at
* runtime. <p>
*
* During deserialization, the fields of non-serializable classes will
* be initialized using the public or protected no-arg constructor of
* the class. A no-arg constructor must be accessible to the subclass
* that is serializable. The fields of serializable subclasses will
* be restored from the stream. <p>
*
* When traversing a graph, an object may be encountered that does not
* support the Serializable interface. In this case the
* NotSerializableException will be thrown and will identify the class
* of the non-serializable object. <p>
*
* Classes that require special handling during the serialization and
* deserialization process must implement special methods with these exact
* signatures: <p>
*
* <PRE>
* private void writeObject(java.io.ObjectOutputStream out)
* throws IOException
* private void readObject(java.io.ObjectInputStream in)
* throws IOException, ClassNotFoundException;
* private void readObjectNoData()
* throws ObjectStreamException;
* </PRE>
*
* <p>The writeObject method is responsible for writing the state of the
* object for its particular class so that the corresponding
* readObject method can restore it. The default mechanism for saving
* the Object's fields can be invoked by calling
* out.defaultWriteObject. The method does not need to concern
* itself with the state belonging to its superclasses or subclasses.
* State is saved by writing the individual fields to the
* ObjectOutputStream using the writeObject method or by using the
* methods for primitive data types supported by DataOutput.
*
* <p>The readObject method is responsible for reading from the stream and
* restoring the classes fields. It may call in.defaultReadObject to invoke
* the default mechanism for restoring the object's non-static and
* non-transient fields. The defaultReadObject method uses information in
* the stream to assign the fields of the object saved in the stream with the
* correspondingly named fields in the current object. This handles the case
* when the class has evolved to add new fields. The method does not need to
* concern itself with the state belonging to its superclasses or subclasses.
* State is saved by writing the individual fields to the
* ObjectOutputStream using the writeObject method or by using the
* methods for primitive data types supported by DataOutput.
*
* <p>The readObjectNoData method is responsible for initializing the state of
* the object for its particular class in the event that the serialization
* stream does not list the given class as a superclass of the object being
* deserialized. This may occur in cases where the receiving party uses a
* different version of the deserialized instance's class than the sending
* party, and the receiver's version extends classes that are not extended by
* the sender's version. This may also occur if the serialization stream has
* been tampered; hence, readObjectNoData is useful for initializing
* deserialized objects properly despite a "hostile" or incomplete source
* stream.
*
* <p>Serializable classes that need to designate an alternative object to be
* used when writing an object to the stream should implement this
* special method with the exact signature: <p>
*
* <PRE>
* ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException;
* </PRE><p>
*
* This writeReplace method is invoked by serialization if the method
* exists and it would be accessible from a method defined within the
* class of the object being serialized. Thus, the method can have private,
* protected and package-private access. Subclass access to this method
* follows java accessibility rules. <p>
*
* Classes that need to designate a replacement when an instance of it
* is read from the stream should implement this special method with the
* exact signature.<p>
*
* <PRE>
* ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;
* </PRE><p>
*
* This readResolve method follows the same invocation rules and
* accessibility rules as writeReplace.<p>
*
* The serialization runtime associates with each serializable class a version
* number, called a serialVersionUID, which is used during deserialization to
* verify that the sender and receiver of a serialized object have loaded
* classes for that object that are compatible with respect to serialization.
* If the receiver has loaded a class for the object that has a different
* serialVersionUID than that of the corresponding sender's class, then
* deserialization will result in an {@link InvalidClassException}. A
* serializable class can declare its own serialVersionUID explicitly by
* declaring a field named <code>"serialVersionUID"</code> that must be static,
* final, and of type <code>long</code>:<p>
*
* <PRE>
* ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
* </PRE>
*
* If a serializable class does not explicitly declare a serialVersionUID, then
* the serialization runtime will calculate a default serialVersionUID value
* for that class based on various aspects of the class, as described in the
* Java(TM) Object Serialization Specification. However, it is <em>strongly
* recommended</em> that all serializable classes explicitly declare
* serialVersionUID values, since the default serialVersionUID computation is
* highly sensitive to class details that may vary depending on compiler
* implementations, and can thus result in unexpected
* <code>InvalidClassException</code>s during deserialization. Therefore, to
* guarantee a consistent serialVersionUID value across different java compiler
* implementations, a serializable class must declare an explicit
* serialVersionUID value. It is also strongly advised that explicit
* serialVersionUID declarations use the <code>private</code> modifier where
* possible, since such declarations apply only to the immediately declaring
* class--serialVersionUID fields are not useful as inherited members. Array
* classes cannot declare an explicit serialVersionUID, so they always have
* the default computed value, but the requirement for matching
* serialVersionUID values is waived for array classes.
*
* @author unascribed
* @version %I%, %G%
* @see java.io.ObjectOutputStream
* @see java.io.ObjectInputStream
* @see java.io.ObjectOutput
* @see java.io.ObjectInput
* @see java.io.Externalizable
* @since JDK1.1
*/
public interface Serializable {
}