Bits of Java (トップ)

目次  前へ  次へ

Serializable オブジェクト以外を直列化しようとした際のエラー

下のプログラムの SerializationSample#main では Serializable オブジェクトではない Book クラスのインスタンスを ObjectOutputStream#writeObject メソッドで直列化しようとしています。 writeObject メソッドの引数は Serializable 型ではなく Object 型なのでコンパイルエラーにはなりません。 SerializationSample を実行すると

Exception in thread "main" java.io.NotSerializableException: Book
        at java.io.ObjectOutputStream.writeObject0(Unknown Source)
        at java.io.ObjectOutputStream.writeObject(Unknown Source)
        at SerializationSample.main(SerializationSample.java:11)
このような例外が発生します。 重要なのは Serializable オブジェクト以外を直列化しようするコードを書いてもコンパイル時には検出されずに実行時に例外が発生するということです。

/**************************** Book.java ****************************/
public class Book {
    protected String title;
    protected String author;
    public Book(String title, String author) {
        this.title  = title;
        this.author = author;
    }
}


/********************* SerializationSample.java *********************/
import java.io.*;

public class SerializationSample {
    public static void main(String[] args) throws Exception {
        Book book = new Book("きまぐれロボット", "星新一");
        ObjectOutputStream out = null;
        try {
            out = new ObjectOutputStream(new BufferedOutputStream(
                                         new FileOutputStream("data")));
            out.writeObject(book);
            out.flush();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {}
            }
        }
    }
}