Serialization

Serialization lets you save an object and all of its instance variables.

How do you know if an object is being instantiated or is being deserialized?

You will be able to know this by overriding readObject() and writeObject() methods. Java serialization has two private methods mentioned beforehand that will be invoked automatically during serialization and deserialization. The serialization system’s callback contract makes sure that these methods will be called.

Here are the method signatures:

private void writeObject(ObjectOutputStream os) {

try {
os.defaultWriteObject();

// custom code as part of serialization
...
...
...
} catch (Exception ex) {
// handle exception
}
}

private void readObject(ObjectInputStream is) {

try {
is.defaultReadObject();

// custom code as part of deserialzation
...
...
...
} catch (Exception ex) {
// handle exception
}
}

When a class is deserialized, the constructor of the class does not run, and the instance variables are NOT given their initially assigned values!

No comments:

Post a Comment

Followers