Saturday, 23 April 2016

Scenarios on Serialization


QUESTION
What happens if one of the member in the class doesn't implement Serializable interface ?
ANSWER
If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a ‘NotSerializableException’ will be thrown at runtime.


QUESTION
If subclass is Serializable but its superclass in not, what will be the state of the instance variables inherited from super class after deserialization ?
ANSWER
Java serialization process only continues in object hierarchy till the class is Serializable.
For example, implements Serializable interface in Java and values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable super class during deserialization process.
Once the constructor chaining will started it wouldn't be possible to stop that, hence even if classes higher in hierarchy implements Serializable interface, there constructor will be executed.


QUESTION
If superclass of a new class implement Serializable interface, how can you avoid new class to being serialized ?
ANSWER
To avoid java serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method.
This is another benefit of customizing java serialization process.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.