Java: Stopping Serialization and Deserialization
There are scenario/ situation where we want to avoid our class to be serialized or deserialized. Like: our class is a singleton and we want to prevent any new object creation.
Note: As we know that deserialization process creates a new object.
Two way to stop serialization process
Method-1: By throwing NotSerializableException:
We write two private methods writeObject/ readObject to just throw the NotSerializableException.
1.1) private void writeObject( ObjectOutputStream oos) throws IOException {
throw new NotSerializableException("This object not support Serialization");
}
1.2) private void readObject( ObjectInputStream ois) throws IOException, ClassNotFoundException {
throw new NotSerializableException("This object not support Serialization");
}
Note: Any attempt to serialize/ deserialize will now always throw the exception.
1.3) Issue: However, this is a violation of the Liskov Substitution Principle.
Method-2: By using writeReplace/ readResolve:
2.1) private Object writeReplace() throws ObjectStreamException {
return this.
}
2.2) private Object readResolve() throws ObjectStreamException {
return this;
}
2.3) Description: In ObjectStream, these methods are used to allow an object to provide an alternative representation for itself.
In other words, writeReplace can be used to change the data that is serialized through writeObject. And readResolve can be used to change the data that is desesrialized through the readObject.
******** END ************************************