Serialization - readObject writeObject overrides
You have to do it like this:
import java.io.IOException;
class Student implements java.io.Serializable {
String name;
String DOB;
int id;
Student(String naam, int idno, String dob) {
name = naam;
id = idno;
DOB = dob;
}
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();
}
public String toString() {
return name + "\t" + id + "\t" + DOB + "\t";
}
}
The readObject is invoked just after creating an instance of Student (bypassing the normal constructor).
I know this question is old, consider this for posterity
Typically you can let the JVM do the hard work by allowing all 'normal' fields to be deserialized automatically:
private void readObject(ObjectInputStream serialized) throws ClassNotFoundException, IOException
{
serialized.defaultReadObject();
// After this, you can handle transient fields or
// special initialization that happens in the constructor
}
The documentation for defaultReadObject()
is quite clear on this:
Read the non-static and non-transient fields of the current class from this stream. This may only be called from the readObject method of the class being deserialized. It will throw the NotActiveException if it is called otherwise.