1. 程式人生 > >Serializable介面--原始碼及翻譯

Serializable介面--原始碼及翻譯

通過實現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;
1
如果writeReplace方法存在,而且它能夠被物件的其它成員方法訪問,則它會被序列化機制呼叫。因此,這個方法可以是private, protected和package-private。

反序列化時,如果需要替換成另一個物件,則需要重寫如下方法:

ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;
1
readResolve的呼叫方式及可訪問特性與writeReplace一樣。

序列化機制會給每個能被序列化的類關聯一個數字型別的版本號,版本號的名字是:serialVersionUID,這個版本號,用於在反序列化時,檢測傳送方和接收方所使用的物件的類是否一致。如果接收方載入的類與傳送方載入的類的serialVersionUID不一致,則反序列化時會丟擲InvalidClassException異常。一個可序列化類可以通過明確的定義一個long型別的,使用static和final修飾的”serialVersionUID”欄位,來指定它的版本號。如下所示:

ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
1
如果一個可序列化類沒有明確的定義一個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 {
}