Default deserialization of of enum types in Java is restricted as the readObject
and readObjectNoData
throw InvalidObjectException
. For this reason enum types are perfect for implementing singleton classes without any flaw (Item 77, Effective Java, 2nd Edition, Bloch).
Serializable
at all?Enum types implement Serializable
so you can serialize objects which contain enum constants. Enum constants are deserialized in the same way as any other objest: by using ObjectInputStream.readObject()
. Enum constants are encoded differently than instances of normal classes, so ObjectInputStream.readObject()
can deserialize them without calling their readObject
method. There are other classes which use special encodings, among them are String
and Class
. See the documentation for more details.
If you want to implement serializable singleton classes yourself, look at readResolve
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With