Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Child classes as Non Serializable in java

I have a class which implements Serializable. Now I extends this class and I want this extended class to be non Serializable. So how to do it?

For example. I have

class A implements Serializable.

and I have

class B extends A.

But I want class B to be Non Serializable.

like image 699
GuruKulki Avatar asked Feb 09 '10 12:02

GuruKulki


People also ask

How do I make my child class non serializable in Java?

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 you prevent a class from being serialized?

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 can you prevent a class from being serialized in Java?

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 we serialize child class in Java?

Yes. If a parent implements Serializable then any child classes are also Serializable .


4 Answers

As others have made clear, it's not possible for a subclass of a Serializable class to be non-Serializable.

If what you want is for the subclass' attributes not to be serialized, one option is to make them all transient.

If you need more than that (you don't want super class fields to be serialized), override writeObject(ObjectOutputStream) and readObject(ObjectInputStream) as outlined here - https://web.archive.org/web/20120626144013/http://java.sun.com/developer/technicalArticles/ALT/serialization

like image 113
Jack Leow Avatar answered Sep 20 '22 13:09

Jack Leow


You can't remove the interface, but you can prevent serialization at run-time:

class B extends A {
    private void writeObject(ObjectOutputStream oos) throws IOException {
        throw new NotSerializableException();
    }
}
like image 40
finnw Avatar answered Sep 21 '22 13:09

finnw


That's indeed not possible. Your best bet is to let B composite/decorate A.

public class B {
    private A a = new A();

    public void doSomething() {
        a.doSomething();
    }
}
like image 37
BalusC Avatar answered Sep 21 '22 13:09

BalusC


Not possible. Liskov Substitution Principle and all.

like image 40
Michael Borgwardt Avatar answered Sep 22 '22 13:09

Michael Borgwardt