Re: Warning about serializing enums with name()
Hendrik Maryns a ??crit :
If you use name() to save an enum reference, you won't be able to
refactor the java [sic] names of the enum constants. So i would advice to
assign an int to each enum constant and serialize that int.
What do you think ?
Enums are serializable, so why bother? But see
The point of your post is: use serialisation but look, serialization
doesn't work that much ?
Huh? Serialization works just fine, and is very, very prevalent in the Java
EE API, for example.
Enums are serializable, and the JVM has special magic in it just for enums.
Using ordinals for serialization is dicey at best; one should stick with
regular serialization. Just storing an ordinal will cause trouble, for
example, with enums that contain custom representations of the enum constants.
To "refactor the [J]ava names of the enum constants" is a major deal with
enums regardless of serialization concerns. You have to make sure all clients
account for the new range of constants. 'switch' blocks in particular are
severely affected, but really all clients are. You just don't undertake
changing an enum lightly.
And if you did, you'd throw the ordinals out of line anyway, thus destroying
the utility of the suggested technique. Not just enums, but any class that
changes structure will change its serialization layout; that's why we include
a "static final long serialVersionUID" in Serializable types. Really,
serializing ordinals is worse than serializing the constants - most enum
refactoring involves adding or deleting constants rather than changing one it