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

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





付録C


トピック:


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

この付録では、既存のクラスをどのように指定および実装すれば既存の実装と相互運用できるかの簡単な例を示します(ファイル名の表現については、Stringと同じ前提は必要ありません)。

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

Fileオブジェクトの直列化状態は、ファイルの直列化可能フィールドおよびデータ値のシーケンスとして定義されます。 この場合は、それぞれ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, 2010, Oracle and/or its affiliates. All rights reserved.