How to stop serialization of subclass if superclass is implementing Serializable
interface?
In order to prevent subclass from serialization we need to implement writeObject() and readObject() methods which are executed by JVM during serialization and deserialization also NotSerializableException is made to be thrown from these methods.
You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.
There is no direct way to prevent sub-class from serialization in java. One possible way by which a programmer can achieve this is by implementing the writeObject() and readObject() methods in the subclass and needs to throw NotSerializableException from these methods.
So if you want to prevent any instance variable from being serialized , do use transient. when you will de-serialize the object it will be initialized with a default value.
You can use writeObject() method to achieve this.
You can use writeObject
customize the serialization behaviour of an object, if you don't wat to allow serialization of an Class
you override this method and throw an error.
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException {
throw new IOException('No serialization not allowed')
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With