简体   繁体   English

Java中枚举字段的序列化

[英]Serialization of enum fields in Java

From the Javadoc of ObjectInputStream : ObjectInputStreamJavadoc中

Enum constants are deserialized differently than ordinary serializable or externalizable objects. 枚举常量的反序列化不同于普通的可序列化或可外部化的对象。 The serialized form of an enum constant consists solely of its name; 枚举常量的序列化形式仅由其名称组成; field values of the constant are not transmitted. 常量的字段值不发送。 To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; 为了反序列化枚举常量,ObjectInputStream从流中读取常量名称。 the deserialized constant is then obtained by calling the static method Enum.valueOf(Class, String) with the enum constant's base type and the received constant name as arguments. 然后,通过以枚举常量的基本类型和接收的常量名称作为参数的静态方法Enum.valueOf(Class,String)来获取反序列化的常量。 Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream. 像其他可序列化或可外部化的对象一样,枚举常量可以用作随后出现在序列化流中的反向引用的目标。 The process by which enum constants are deserialized cannot be customized: any class-specific readObject, readObjectNoData, and readResolve methods defined by enum types are ignored during deserialization. 无法自定义反序列化枚举常量的过程:反序列化期间,将忽略由枚举类型定义的任何特定于类的readObject,readObjectNoData和readResolve方法。 Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored--all enum types have a fixed serialVersionUID of 0L. 同样,任何serialPersistentFields或serialVersionUID字段声明也将被忽略-所有枚举类型的固定serialVersionUID为0L。

Why are enums in Java not serialized on their entirety? 为什么Java中的枚举没有全部序列化? Enums in Java are more than mere constants and are full fledged classes that can also contain state. Java中的枚举不仅是常量,而且是可以包含状态的完整类。 Does it not result in inconsistent state between the sending and the receiving ends? 是否不会导致发送端和接收端之间状态不一致? What is that fundamental point that I am missing here? 我在这里缺少的基本点是什么?

The lesson is to not use enums when you need mutable objects. 课程是在需要可变对象时不要使用枚举。 Yes, you can design enums that maintain an internal state, but they weren't designed for that. 是的,您可以设计维护内部状态的枚举,但并不是为此而设计的。 As in the case of serialization, not all parts of Java will cooperate if you do. 与序列化的情况一样,如果您这样做,并非Java的所有部分都可以配合使用。

If you must tie enum values to state data, use an EnumMap . 如果必须将enum值绑定到状态数据,请使用EnumMap That class implements Serializable , so you won't need to do any additional work to serialize your state data (provided the state data objects are themselves serializable). 该类实现Serializable ,因此您不需要做任何其他工作即可序列化状态数据(前提是状态数据对象本身可序列化)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM