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.
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.
Yes. If a parent implements Serializable then any child classes are also Serializable .
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
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();
}
}
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();
}
}
Not possible. Liskov Substitution Principle and all.
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