序列化枚举 [英] Serializing enums

查看:152
本文介绍了序列化枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个序列化的对象,我添加了一个枚举。这使得它不再与旧版本的软件兼容。我相信这是因为旧版本是用Java 1.4编译的。我得到:

  java.io.InvalidClassException:不能将枚举描述符绑定到非枚举类

理想情况下,我想用一个String替换枚举,并以某种方式修复现有对象。



有几个想法是:


  1. 阅读序列化对象,忽略该枚举的字段。该值将丢失,但这是可以的。


  2. 有两个序列化类的副本,重命名一个与枚举,并以某种方式将对象读入新的



解决方案

只需标记枚举字段为 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:

  1. When reading the serialized object, ignore the field with the enum. The value would be lost, but that's OK.

  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆