目次 | 前の項目 | 次の項目 Java オブジェクト直列化仕様
Version 6.0

直列化可能フィールドの例





付録 C


トピック:


C.1 java.io.File 代替実装の例

ここでは、既存のクラスを指定および実装して、既存の実装との相互運用を可能にする簡単な例を示します。ただし、ファイル名の表現に関しては、その前提が String の場合と同じでなくてもかまいません。

システムクラス java.io.File は、1 つのファイル名を表現し、また構文解析用のメソッドを持ちます。このクラスを使って、名前でファイルとディレクトリを操作できます。このクラスには、現在のファイル名を含む単一の private なフィールドがあります。パスを解析するメソッドのセマンティクスは、静的フィールドに保持された現在のパス区切り文字に依存します。このパス区切り文字はファイルの直列化状態の一部で、読み込み時にファイル名を調節するために必要です。

File オブジェクトの直列化状態は、そのファイルの直列化可能フィールドおよびデータ値のシーケンスとして定義されます。この場合は、1 つの直列化可能フィールドおよび 1 つのデータ値のシーケンスがあります。

Serializable Fields:
    String path;     // path name with embedded separators
Serializable Data:
    char            // path name separator for path name
An alternate implementation might be defined as follows:
class File implements java.io.Serializable {
    ...
    private String[] pathcomponents;
    // Define serializable fields with the ObjectStreamClass
    
	/**
	 * @serialField path String 
     *              Path components separated by separator.          
     */
	private static final ObjectStreamField[] serialPersistentFields
        = { new ObjectStreamField("path", String.class) };
    ...
	/**
      * @serialData  Default fields followed by separator character.             
    */ 
    private void writeObject(ObjectOutputStream s)
        throws IOException
    {
        ObjectOutputStream.PutField fields = s.putFields();
        StringBuffer str = new StringBuffer();
        for(int i = 0; i < pathcomponents; i++) {
            str.append(separator);
            str.append(pathcomponents[i]);
        }
        fields.put("path", str.toString());
        s.writeFields();
        s.writeChar(separatorChar); // Add the separator character
    }
    ...
    private void readObject(ObjectInputStream s)
        throws IOException
    {
        ObjectInputStream.GetField fields = s.readFields();
        String path = (String)fields.get("path", null);
        ...
        char sep = s.readChar(); // read the previous separator char
        // parse path into components using the separator
        // and store into pathcomponents array.
    }
}


目次 | 前の項目 | 次の項目
Copyright © 2005 Sun Microsystems, Inc. All Rights Reserved.