Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialization of enum in Java

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).

  • Why, on the first hand, enum types implement Serializable at all?
  • How should be enum references deserialized in practice?
like image 894
abksrv Avatar asked Jul 21 '13 13:07

abksrv


1 Answers

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.

like image 96
abacabadabacaba Avatar answered Oct 03 '22 11:10

abacabadabacaba