In a previous article Everything You Need to Know About Java Serialization, we discussed how serializability of a class is enabled by implementing the
Serializable interface. If our class does not implement
Serializable interface or if it is having a reference to a non
Serializable class then JVM will throw
All subtypes of a serializable class are themselves serializable and
Externalizable interface also extends Serializable. So even if we
customize our serialization process using Externalizable our class is still a
Serializable interface is a marker interface which has no methods or fields and it works like a flag for the JVM. The Java serialization process provided by
ObjectOutputStream classes are fully controlled by the JVM.
But what if we want to add some additional logic to enhance this normal process, for example, we may want to encrypt/decrypt our sensitive information before serializing/deserializing it. Java provides us with some additional methods for this purpose which we are going to discuss in this blog.
writeObject and readObject methods
Serializable classes that want to customize or add some additional logic to enhance the normal serialization/deserialization process should provide
readObject methods with these exact signatures:
private void writeObject(java.io.ObjectOutputStream out) throws IOException
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
These methods are already discussed in great details under article Everything You Need to Know About Java Serialization.
As described in Java docs of
Serializable class, if we want to initialize the state of the object for its particular class in the event that the serialization stream does not list the given class as a superclass of the object being deserialized then we should provide
readObject methods with these exact signatures:
private void readObjectNoData() throws ObjectStreamException
This may occur in cases where the receiving party uses a different version of the deserialized instance’s class than the sending party, and the receiver’s version extends classes that are not extended by the sender’s version. This may also occur if the serialization stream has tampered; hence, readObjectNoData is useful for initializing deserialized objects properly despite a “hostile” or incomplete source stream.
Each serializable class may define its own
readObjectNoData method. If a serializable class does not define a
readObjectNoData method, then in the circumstances listed above the fields of the class will be initialized to their default values.
writeReplace and readResolve methods
Serializable classes that need to designate an alternative object to be used when writing an object to the stream should provide this special method with the exact signature:
ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException
And Serializable classes that need to designate a replacement when an instance of it is read from the stream should provide this special method with the exact signature:
ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException
writeReplace method allows the developer to provide a replacement object that will be serialized instead of the original one. And the
readResolve method is used during deserialization process to replace the de-serialized object by another one of our choices.
One of the main usages of writeReplace and readResolve methods is to implement the singleton design pattern with Serialized classes. We know that the deserialization process creates a new object every time and it can also be used as a method to deeply clone an object, which is not good if we have to make our class singleton.
You can read more about Java cloning and serialization on Java Cloning and
Java Serialization topics.
readResolve is called after
readObject has returned (conversely
writeReplace is called before
writeObject and probably on a different object). The object the method returns replaces
this object returned to the user of
ObjectInputStream.readObject and any further back-references to the object in the stream. We can use the writeReplace method to replace serializing object with null so nothing will be serialized and then use the readResolve method to replace the deserialized object with the singleton instance.
If we want to perform certain validations on some of our fields we can do that by implementing
ObjectInputValidation interface and overriding
validateObject method from it.
validateObject will automatically get called when we register this validation by calling
ObjectInputStream.registerValidation(this, 0) from
readObject method. It is very useful to verify the stream has not been tampered with, or that the data makes sense before handing it back to your application.
Below example covers code for all above methods
You can find the complete source code for this article on this
Github Repository and please feel free to provide your valuable feedback.
Published on Java Code Geeks with permission by Naresh Joshi, partner at our JCG program. See the original article here: Java Serialization Magic Methods And Their Uses With Example
Opinions expressed by Java Code Geeks contributors are their own.