Bits of Java (トップ)

目次  前へ  次へ

Unserializable スーパークラスのフィールドが直列化、復元されない例

下の SubBook クラスは Serializable インターフェイスを実装していますがそのスーパークラスの Book クラスは Serializable インターフェイスを実装していません。 この結果 SubBook オブジェクトを直列化、復元すると Book で定義されているフィールド title author に関しては直列化時の値はすべて失われ、 復元後の値は SubBook のデフォルトコンストラクタの実行後の値である null になってしまいます。
BookSerializeSample の実行結果は以下です。

SubBook title:null  author:null  price:357
これに対する対処は次のページで行います。

/**************************** Book.java ****************************/
public class Book {
    protected String title;
    protected String author;

    protected Book() {}
    public Book(String title, String author) {
        this.title  = title;
        this.author = author;
    }
//--------------------------------------------------------------------
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
//--------------------------------------------------------------------
    public String toString() {
        return "Book title:" + title + "  author:" + author;
    }
}


/**************************** SubBook.java ****************************/
public class SubBook extends Book implements java.io.Serializable {
    protected int price;
    public SubBook(String title, String author, int price) {
        super(title, author);
        this.price = price;
    }
//--------------------------------------------------------------------
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
//--------------------------------------------------------------------
    public String toString() {
        return "SubBook title:" + title + "  author:" + author +
               "  price:" + price;
    }
}

/********************* BookSerializeSample.java *********************/
import java.io.*;

public class BookSerializeSample {
    public static void main(String[] args) throws Exception {
        SubBook book = new SubBook("きまぐれロボット", "星新一", 357);
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        try {
            out = new ObjectOutputStream(new BufferedOutputStream(
                                         new FileOutputStream("data")));
            out.writeObject(book);
            out.close();
            out = null;

            in = new ObjectInputStream(new BufferedInputStream(
                                       new FileInputStream("data")));
            System.out.println(in.readObject());

        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {}
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {}
            }
        }
    }
}