I’m going through serialization and I can’t understand the following:
I don’t understand why the output of this code is:
import java.io.*;
public class InnerOuterTest {
public static ObjectOutputStream out;
public static ObjectInputStream in;
static {
try {
out = new ObjectOutputStream(new FileOutputStream("save.ser"));
in = new ObjectInputStream(new FileInputStream("save.ser"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
try {
ShouldForgive f = new ShouldForgive();
f.x = 5;
write(f);
ShouldForgive g = read();
System.out.println(g.x);
f.x = 0;
g.x=8;
write(f);
ShouldForgive v = read();
System.out.println("is "+v.x);
} finally {
out.close();
in.close();
}
}
private static void write(ShouldForgive f) throws IOException {
out.writeObject(f);
}
public static ShouldForgive read() throws ClassNotFoundException, IOException {
return (ShouldForgive) in.readObject();
}
}
class ShouldForgive implements Serializable {
int x = -1;
}
Is
5
8
And not
5
0
I tried f == g which returns false and if I reset the input stream. I found out that if I implement readObject it is only called once… I don’t understand this behavior. (Why is the object only read once?)
I get the feeling that serialization only happens once… How is the object tracked? Even if I implement readObject and writeObject without actually reading or writing from the file I still get 8
If you call
out.reset()after the first write, you will get the behaviour you are expecting, or if you usewriteUnshared()instead ofwriteObject(). Objects that have already been written to the stream are not rewritten; instead a ‘handle’ to the previously written object is written. See the Javadoc for details.