Reputation: 40
Is there a way where I can prevent the parent class to be serialized?
When we do a serialization of the subclass all the way up till the parent class the serialization is performed.
Can I restrict the serialization of the parent classes and serialize the only sub class I am working on?
Upvotes: 0
Views: 1820
Reputation: 140457
Whilst it is technically possible to fine tune each level of inheritance on its own - even to the extent of excluding super class fields - you might want to step back here.
Basically there are two cases:
So how do you think to meaningfully address the second part? You see when you allow deserialisation without the data for the super class fields - that means that you might have to do a lot of additional testing. To make sure that super class methods don't throw exceptions - because all of a sudden fields are null instead of being initialized.
In other words: it is possible that "leaving out" all these values - you are creating objects which behave completely different. Are you prepared for handling all the effects of that?
Meanung: skipping super class fields requires you to interfere with serialization code. It might require a lot of additional testing effort. And what do you gain? A few bytes less of data transfer at runtime.
Beyond that: what is the purpose of an inheretance hierarchy that has 4 levels - but where the super class state is irrelevant?
So my non-answer: carefully consider if your idea is really the best OO design to solve the underlying requirements.
Upvotes: 0
Reputation: 310907
It is possible. Just declare your class as implements Externalizable
and write exactly what you need in the writeExternal()
method, taking care not to serialize anything from the superclass, and read exactly that back in the readExternal()
method.
Or, just implement Serializable
and provide your own readObject()/writeObject()
methods, again taking care not to serialize anything from the superclass, and in this case also not calling defaultWriteObject()
or defaultReadObject()
.
In both cases the actual serialization of the current class's data is entirely up to you.
Upvotes: 4