@ColinD is kind of right, but his answer also illustrates why singletons don't really jell with serialization.
Here's what happens when you serialize an enum value (see here).
The rules for serializing an enum instance differ from those for serializing an "ordinary" serializable object: the serialized form of an enum instance consists only of its enum constant name, along with information identifying its base enum type. Deserialization behavior differs as well--the class information is used to find the appropriate enum class, and the Enum.valueOf method is called with that class and the received constant name in order to obtain the enum constant to return.
So any additional state that you attach to your enum values does not survive serialization and deserialization.
You could do the same thing yourself, by adding custom serialization / deserialization code to your singleton classes. That code would need to either not record the singleton's state at all, or throw it away when the singleton is deserialized. Either way, you'd put the logic into a readResolve()
method as explained by @ColinD's answer.
However, I presume that the reason you want to serialize singletons is that you want to persist their state. Unfortunately, that presents a conceptual problem. Suppose that your application has instantiated the singleton in the normal course of events, and then it deserializes some object graph that includes a copy of a previous instance of the singleton. What can it do?
- If it deserializes the singleton normally, it violates "singleton-ness".
- If it doesn't then the application cannot access the singleton's previous state.