Reputation: 422
I have one class Object and persisted it. Now I want to make super class of that existing class and moved one field to parent class.
When I am de-serializing the object it's giving that field value as null.
Class A{
int a;
String b;
}
I persisted this class object.
I create new class.
Class B{
String b;
}
I extend B class to A.
class A extends B{
int a;
}
Now when I want to de-serialize the existing stored object, it is giving b field value as null;
Upvotes: 2
Views: 3257
Reputation: 718986
All sorts of bad things can happen if you make a significant change to a class when there are serialized instances of the old version.
In this case, you have made an incompatible change at the representation level, but (in effect) told the serialization system that the old and new representations are compatible ... because you are using the same serialVersionUID value in the old and new versions of the class.
I'm also guessing that while class A
(the subclass) implements Serializable
, class B
(the superclass) does not. When a serializable class has a non-serializable superclass, the fields of the superclass don't get serialized. When the class is de-serialized, the non-serializable superclasses no-args constructor is invoked. In your example, the B
constructor must be initializing (or default initializing) the field b
to null
.
Getting versioning right with serialization is tricky. If you are contemplating making changes to serializable classes AND you want to be able to use previously serialized objects, then you should read Chapter 5 of the Object Serialization Specification carefully. In fact, you should probably read the entire spec.
In general Java Object Serialization is not a good choice if there is any possibility that you will need to evolve the serializable classes. Text-based serialization schemes (like JSON or XML) are more robust and more "forgiving". Alternatively, a database may be a better choice.
Upvotes: 2
Reputation: 597
Java's serialization API unfortunately is not designed for this kind of change to the code. I would recommend serializing to JSON or something if you're going to be making changes like this. It's more work, but I would say it's worth it for future-proofing.
Upvotes: 0
Reputation: 310957
when I want to de-serialize the existing stored object, it is giving b field value as null;
This behaviour is correct. You've added a field to the parent and removed one from the child. Added fields are deserialized as null from streams that don't contain them, and removed fields are ignored when encountered in streams that contain them.
You need to read the Versioning of Serializable Objects chapter of the Object Serialization Specification.
Upvotes: 0