Issues with objects serialization
I have an issue when saving the object serialization then loading it again..
First i have class with originally the following string "A", "B", "C" I saved it with some d开发者_如何学Cata to file...
Later I modified the class so it has one more string "D". After I load the file that I saved before I modified the application does not know about the new string "D"...
What is the best mechanism to handle such an issue... It will be very lengthy to copy the data from the old object to the new one... I want to make the saved object know that there was some structure changes...
Any help please...
Use a different serialVersionUID
to tell the system there's a different version.
From the JavaDoc on Serializable:
The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
(Markup by me)
Edit:
As an alternative you could just use another field to store the version and deserialize despite the class changes. In that case the new string should be initialized to null. You could then check the version to see whether the string was present in the previous version and just was null when saving or whether there was a structural change in between.
Example:
class MyObject {
private static final versionUid = 1;
private final int version;
private String a, b, c, d; //plus getters/setters;
public MyObject() {
version = versionUid ; //needed if you want to load objects of different backward compatible versions and still know the version after deserialization
}
public int getVersion() {
return version;
}
}
MyObject readObjectOfVersion2 = ... ;//deserialize an object of version 1
if( readObjectOfVersion2.getVersion() > 1 ) {//assuming version 1 only has a,b,c and version 2+ has d as well
String d = readObjectOfVersion2.getD();
}
精彩评论