Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop serialization of subclass? [duplicate]

How to stop serialization of subclass if superclass is implementing Serializable interface?

like image 615
AmitG Avatar asked Apr 02 '13 09:04

AmitG


People also ask

How do you prevent a serialized subclass?

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.

How can we prevent serialization?

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.

How do you restrict class in serialization?

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.

How can we avoid variables in serialization in Java?

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.


1 Answers

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')
}
like image 104
Arun P Johny Avatar answered Nov 15 '22 02:11

Arun P Johny