How to prevent subclass from serialization in java

Views: 159   

In Java, if the super class of a class is implementing Serializable interface, it means that it is already serializable. Since it is not possible to make a class as non serializable. However, the serialization of a new class can be avoided. For this, we have to write writeObject () and readObject() methods in your class so that it will not Serializable, Exception can be thrown by these methods. This can be done by customizing the Java Serialization process. Below the code that demonstrates it

import java.io.*;
class SuperClass implements Serializable {

   //  some code here
}
class MySubClass extends SuperClass {
    private void writeObject(ObjectOutputStream out)
         throws IOException {
     throw new NotSerializableException(“Can not serialize this class”);
    }
     private void readObject(ObjectInputStream in)
         throws IOException, ClassNotFoundException {
     throw new NotSerializableException(“Can not serialize this class”);
    }
    }
On By