これが私のコードです:
class Collar {
int size;
}
class Dog implements Serializable {
int weight;
transient Collar c;
public Dog(int weight, int size) {
this.weight = weight;
c = new Collar();
c.size = size;
}
public void writeObject(ObjectOutputStream os) throws Exception {
os.defaultWriteObject();
os.writeInt(c.size);
}
public void readObject(ObjectInputStream is) throws Exception {
is.defaultReadObject();
c = new Collar();
c.size = is.readInt();
}
}
public class test {
public static final String FILE_REVISION = "$Revision$";
public static void main(String ar[]) throws Exception {
Dog dOut = new Dog(20, 2);
System.out.println("DOut Weight: " + dOut.weight + " Size: " + dOut.c.size);
FileOutputStream fo = new FileOutputStream("Dog.ser");
ObjectOutputStream os = new ObjectOutputStream(fo);
os.writeObject(dOut);
FileInputStream fi = new FileInputStream("Dog.ser");
ObjectInputStream is = new ObjectInputStream(fi);
Dog dIn = (Dog) is.readObject();
System.out.println("DIn Weight: " + dIn.weight + " Size: " + dIn.c.size);
}
}
出力は次のとおりです。
DOut Weight: 20 Size: 2
Exception in thread "main" java.lang.NullPointerException
at test.main(test.java:55)
行 55 は、System.out.println() を持つコードの最後の行です。
プログラムはシリアライズ可能なオブジェクト、ここでは Dog を取得できます。ただし、カスタムの readObject メソッドを使用して読み返すと、新しい「格納」オブジェクトである Collar を作成できません。どこが間違っていますか?
ご覧のとおり、出力は 'dIn.c.size' ステートメントの NullPointerException です。カスタムreadObjectメソッドでcを新しいオブジェクトとして設定していますが、実際には機能していません。