ObjectOutputStream#writeObject メソッドで直列化する際には transient フィールドと static フィールド以外のフィールドが直列化されます。 直列化の際には直列化しようとしたフィールドがプリミティブ型や Serializable オブジェクトではない場合には例外が発生します。 そこで Serializable インターフェイスを実装したクラスでは static フィールド以外のすべてのフィールドを直列化する場合を除いて直列化を行うフィールドを指定するかその逆に直列化を行わないフィールドを指定するかのどちらかが必要になります。
Book クラスではフィールド object を transient キーワードで修飾することで直列化を行わないことを明示しています。 transient を指定したフィールドは ObjectOutputStream#writeObject メソッドにおいて直列化が行われません。
BookSerializeSample の実行結果は以下です。
Book title:きまぐれロボット author:星新一 object:null復元後のオブジェクトには直列化時の object のデータが失われています。 このように直列化を行わなかったフィールドは数値型なら 0 に boolean 型なら false に参照型なら null になります。
/**************************** Book.java ****************************/
public class Book implements java.io.Serializable {
protected String title;
protected String author;
protected transient Object object = new Object();
public 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 +
" object:" + object;
}
}
/********************* BookSerializeSample.java *********************/
import java.io.*;
public class BookSerializeSample {
public static void main(String[] args) throws Exception {
Book book = new Book("きまぐれロボット", "星新一");
ObjectOutputStream out = null;
ObjectInputStream in = null;
try {
out = new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream("bookdata")));
out.writeObject(book);
out.close();
out = null;
in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream("bookdata")));
System.out.println(in.readObject());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {}
}
}
}
}