How can I have more flexible serialization and deserialization in Java?
If I serialize an object in Java, and then later add an extra field to the java class, I can't deserialize the object into the modified class.
Is there a serialization library or some way that I can have deserialization be less strict, like if开发者_如何转开发 there is an extra field added to the class then it just fills that with null upon deserialization of the old version of the class?
You need to keep a serialVersionUID
on your class. Check out the section "Version Control" in this article by Sun.
You've got lots of potential options.
You could use a graph serialisation library to define and manage your format e.g. Google's protocol buffers or Kryo. I believe both of these have built-in support for versioning.
You can write your own custom serialisation code and handle the versions explicitly - e.g. serializing to a flexible format like XML. When reading the XML you can configure it to use default values if a particular field isn't specified.
Or you could design your class in a "flexible" way, e.g. have all the fields stored in a HashMap and indexed by Strings. Depending on what you are trying to do, this may be a convenient option.
There's a fair few serialization libraries, take a look at Simple though:
http://simple.sourceforge.net/
or as mentioned above Google Protocol Buffers.
http://code.google.com/apis/protocolbuffers/
Implement Externalizable and you can do whatever you want. The puts the onus of serial/deserialization completely upon the class being serialized.
Did you add a serialVersionUID? This must be present (and unchanged) if you want to serialize / deserialize different Versions of a class.
Furthermore you can add the following two methods to your class to define exactly the serialization process:
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException;
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException;
The Javadoc of ObjectInputStream gives more detail on its usage.
If I serialize an object in Java, and then later add an extra field to the java class, I can't deserialize the object into the modified class.
That's untrue for a start. You need to have a good look at the Versioning section of the Object Serialization specification before you go any further.
精彩评论