Enumeration Serialization

I have a serialized object to which I have added an enumeration. This makes it more incompatible with older versions of software. I believe this is due to the fact that the old version was 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 enum with String and somehow fix the existing object.

A few ideas:

  • When reading a serialized object, ignore the enumeration field. The value will be lost, but it’s OK.

  • Have two copies of the serialized class, renaming one with an enumeration and somehow reading the object in the newly renamed class.

+4
source share
3 answers

Just mark the enum field as transient . It will not be serialized.
You will lose this value, but you said you did not mind.

transient is the Java keyword.
He places the field as something that should not be considered as part of the constant state of the object.
He notes a member variable that should not be serialized when it is stored in byte streams. When an object is transmitted over the network, the object must be serialized. Serialization converts the state of an object into consecutive bytes. These bytes are transmitted over the network, and the object is recreated from these bytes. Participant variables marked with the java transient keyword are not migrated; they are intentionally lost. [ source ]

+3
source

I believe this is because the version is compiled with Java 1.4. I will get:

No. There were no enumerations in Java 1.4.1. They were introduced in 1.5. It seems that what happened was that what was serialized as String was subsequently changed to Enum.

Ideally, I would like to replace the enum with the string

Your proposed change simply cancels this.

and somehow fix the existing object.

You cannot fix an existing serialized object, but you can make the current class compatible with it by returning the source code or finding out what it should have been and declaring identical serialVersionUID.

+2
source

The simplest solution would be to read serialized objects using your new code and write it in a format that your old software version understood. Of course, if this is not a viable solution, you may need to clarify your requirements a bit more. How in what parts can be changed, what cannot be changed, etc.

0
source

All Articles