问题
From the Javadoc of ObjectInputStream:
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; 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. 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. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored--all enum types have a fixed serialVersionUID of 0L.
Why are enums in Java not serialized on their entirety? Enums in Java are more than mere constants and are full fledged classes that can also contain state. Does it not result in inconsistent state between the sending and the receiving ends? What is that fundamental point that I am missing here?
回答1:
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.
If you must tie enum
values to state data, use an 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).
来源:https://stackoverflow.com/questions/18361190/serialization-of-enum-fields-in-java