I'm trying to understand java serialization mechanism, and I have few doubts
kindly answer the following questions regarding java serialization:
- Why we use
oos.defaultWriteObject();
? According to this post its there for backward compatibility. And I don't quite understand how it achieves that.one of incompatible changes for serialization is deleting a field in the newer version. Which means the older versions will have to set default values which sometimes invalid for the user.how is this any different than newer versions adding a new field and allowed to set default values? - during custom serialization does it make any difference to use both
oos.defaultWriteObject();
andoos.writeObject(address);
doesn't the both does the same thing ? I mean both writes non-transient non-static fields of all super class and current class to OOS.
here
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException {
stream.writeObject(name);
stream.writeInt(id);
stream.writeObject(DOB);
}
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
name = (String) stream.readObject();
id = stream.readInt();
DOB = (String) stream.readObject();
}
the above code produces the same result as the below code
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException {
stream.defaultWriteObject();
}
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
}
when to use those 2 methods , when to use just writeObject(employee);//employee is my whole object//
- here is the list of possible duplicate questions which doesn't answer my question.
- question 1 it says * If defaultWriteObject or writeFields is not invoked once before the writing of optional data (if any), then the behavior of instance deserialization is undefined in cases where the ObjectInputStream* but I can still call writeObject without using deafultwriteobject.right ?
- question 2 these answers say that defaultwriteobject method writes some extra data to stream and it reflectively checks what to write. doesn't the oos.writeobject(object obj) also reflectively check?
- Finally i can get control of my serialization by overriding writeObject and ReadObject method, then whats the point of Externalizable ?
- If providing serial versionUID does not throw exception what will happen if i deserialize an object which has missing field from older class which has that field, basically what will happen to all incompatible changes if i provide my own SerialverUID ? is it having own serial version UID will not throw streamcorrupted exception for all compatible changes ?