2

there are lots of toturials about enum and serialization, I also read the article in sun, but not able to find how to serialize it.

Enum constants are serialized 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 present in the form. To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method. To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java.lang.Enum.valueOf method, passing the constant's enum type along with the received constant name as arguments.

any example will appreciate.

shiv
  • 477
  • 5
  • 17
  • What is your issue exactly? You can serialize an enum without any addition, what have you tried that it's not working? – EsotericVoid Jul 20 '17 at 15:46
  • @Bit as above statmement saying "Enum constant are serialized diffrent" what is meaning of that. what is difference b/w normal serialization then enum. – shiv Jul 20 '17 at 15:49
  • here we go, so your actual question is "How are enums serialized in Java?". You can find sort of an answer here https://stackoverflow.com/a/15522276/6768966. The "I also read the article in sun, but not able to find how to serialize it." part is misleading, it looks like you don't know the how, not the why. – EsotericVoid Jul 20 '17 at 15:53
  • I think he means that only the name of the enum value is serialized and preserved. If you create a constructor which keeps any kind of data with the enum, that data its not serialized and this not preserved. – gmanjon Jul 20 '17 at 15:53
  • Possible duplicate https://stackoverflow.com/questions/15529490/custom-fields-on-java-enum-not-getting-serialized – gmanjon Jul 20 '17 at 15:57

1 Answers1

3

All enum types implicitly extend java.lang.Enum which already implements Serializable. Thus you have no specific action to take, it's already done for you.

corsiKa
  • 81,495
  • 25
  • 153
  • 204
  • then why there is buzz over enum and serialization, as I mention in question. – shiv Jul 20 '17 at 15:47
  • 1
    Because the implementation is done in a very efficient fashion - people might be tempted to write their own serialization and include things that are unnecessary. Since you need the class on the receiving end anyway, there's no need to include anything but the enum constant. (You could further optimize it to ordinal, but there could be problems with different versions of the class having inserted items...) – corsiKa Jul 20 '17 at 15:49