序列化枚举 [英] Serializing enums
问题描述
java.io.InvalidClassException:不能将枚举描述符绑定到非枚举类
理想情况下,我想用一个String替换枚举,并以某种方式修复现有对象。
有几个想法是:
-
阅读序列化对象,忽略该枚举的字段。该值将丢失,但这是可以的。
-
有两个序列化类的副本,重命名一个与枚举,并以某种方式将对象读入新的
只需标记枚举
字段为 transient
。它不会被序列化。
你会失去这个价值,但你说你不介意。
transient
是一个Java关键字。
标志一个字段不应被视为对象持久状态的一部分。
它标记一个成员变量不被序列化,当它被持续到字节流时。当通过网络传输对象时,对象需要串行化。序列化将对象状态转换为串行字节。这些字节通过网络发送,并且从这些字节重新创建对象。由java transient关键字标记的成员变量不传输,故意丢失。 [来源]
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]
这篇关于序列化枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!