Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to mark an inherited class as NOT serializable

Tags:

java

If I inherit from a class that is serializable but I specifically do not want my class to be serializable; what's the best way to strictly prevent serialization?

If there was a method in java.io.Serializable maybe I could throw an exception, but Serializable is empty.

like image 241
initialZero Avatar asked Mar 12 '10 22:03

initialZero


People also ask

How do you make a class non serializable?

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 do you restrict child class from 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.

Can serializable class inherited?

You must explicitly mark each derived class as [Serializable] . If, however, you mean the ISerializable interface, then yes: interface implementations are inherited, but you need to be careful - for example by using a virtual method so that derived classes can contribute their data to the serialization.

What happens if your serializable class contains a member which is not serializable?

It'll throw a NotSerializableException when you try to Serialize it. To avoid that, make that field a transient field.


1 Answers

From the documentation

Serialization of an object can be prevented by implementing writeObject and readObject methods that throw the NotSerializableException. The exception will be caught by the ObjectOutputStream and abort the serialization process.

like image 125
Steven Schlansker Avatar answered Sep 28 '22 02:09

Steven Schlansker