I have a serialized object which I added an enum to. This makes it no longer compatible with older 开发者_高级运维versions of the software. I believe this is because the older version is compiled with Java 1.4. I get:
java.io.InvalidClassException: cannot bind enum descriptor to a non-enum class
Ideally I would like to replace the enum with a String and somehow fix the existing object.
A couple of ideas are:
When reading the serialized object, ignore the field with the enum. The value would be lost, but that's OK.
Have two copies of the serialized class, renaming the one with the enum and somehow read the object into the newly renamed class.
Just mark the enum
field as transient
. It won't get serialized.
You will lose that value, but you said that you don't mind.
transient
is a Java keyword.
It flags a field as something that should not be considered part of an object's persistent state.
It marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost intentionally. [source]
I believe this is because the older version is compiled with Java 1.4. I get:
No. There were no enums in Java 1.4.1. They were introduced in 1.5. What appears to have happened is that something that was serialized as a String was subsequently changed to an Enum.
Ideally I would like to replace the enum with a String
Your proposed change just reverses that.
and somehow fix the existing object.
You can't fix the existing serialized object, but you can make the current class compatible with it, by reverting the source, or figuring out what it must have been and declaring an identical serialVersionUID.
The simplest solution would be to read the serialized entities using your new code and write it out in a format which is understandable by your old version of software. Of course, if this isn't a viable solution, you might need to clarify your requirements a bit more. As in what parts can be changed, what can't be changed etc.
精彩评论