next up previous contents
Next: ObjectStreamClass Up: Serialization Previous: 簡単なサンプル

オブジェクトを「保存」「復元」するとは?

オブジェクトを永続的に、Javaの仮想マシンの外部に保存し、後でそれを復元する には、いろいろなやり方が考えられます。JDK1.1で採用された方式を、少し詳しく見て 行きたいのですが、ここでは、まず二つのことに注目しましょう。

プリミティブ・タイプの場合

第一に、保存すべき対象が、プリミティブ・タイプの場合には、ストリームへの 書き出しは比較的単純な方法で可能です。新しいクラスを作らずとも、 DataOutputStreamクラスには、既に、次のようなメソッドが用意されています。

==========================================================================
    public final boolean writeBoolean() throws IOException ;
    public final byte writeByte() throws IOException ;
    public final short writeShort() throws IOException ;
    public final char writeChar() throws IOException ;
    public final int writeInt() throws IOException ;
    public final long writeLong() throws IOException ;
    public final float writeFloat() throws IOException ;
    public final double writeDouble() throws IOException ;
    public final String writeUTF() throws IOException ;
==========================================================================
同様に、ストリームからプリミティブ・タイプを復元するには、次のような メソッドを備えた DataInputStreamを利用すれば充分です。
==========================================================================
    public final boolean readBoolean() throws IOException ;
    public final byte readByte() throws IOException ;
    public final short readShort() throws IOException ;
    public final char readChar() throws IOException ;
    public final int readInt() throws IOException ;
    public final long readLong() throws IOException ;
    public final float readFloat() throws IOException ;
    public final double readDouble() throws IOException ;
    public final String readUTF() throws IOException ;
==========================================================================

最後のwriteUTF/readUTFメソッドは、Stringを、UTFというプラットフォームに依存 しないフォーマットで、ストリームに読み書きする為のものです。 実際、SerializationをになうObjectOutputStreamも、DeSerializationをになう ObjectInputStreamも、内部的には、これらのメソッドの一部を呼び出して、 DataOutputStream,DataInputStreamの機能を利用しています。

フィールドの値の保存・復元

第二に重要なことは、オブジェクトの状態を保存するということは、クラスの フィールドの値を保存することだということです。クラスは、一般には、フィールド とメソッドとコンストラクタからできているのですが、オブジェクトの状態に関係 するのはフィールドだけです。逆に、クラスの名前とフィールドの値さえ分かれば、 元のオブジェクトを復元することは可能です。確かに、クラスの名前が分かっても、 保存した時のクラスのバージョンと、復元しようとした時のクラスのバージョンが 違っている可能性もあるのですが、細かいことは後でゆっくり見ることにしましょう。



maruyama@wakhok.ac.jp