Custom fields in java enumeration don't get serialized

I have a Java Enum as shown below:

public enum ExecutionMode { TYPE_A, TYPE_B, TYPE_C; private ExecutionMode(){} //no args constr- no really required private boolean incremental; //has get/set private String someStr; //has get/set } 

I see that after deserialization the user fields in the enumeration are lost. When I read more about this, I got the impression that enum gets deserialized into a string, and therefore its user fields are ignored.

If this is true, am I abusing Enum here and should just use POJO istead? Or is there a way to serialize custom fields (which are not part of the constructor)?

Thanks!

+6
source share
2 answers

If the values ​​are constant, it is better and you do not need to serialize anything

 public enum ExecutionMode { TYPE_A(x,t), TYPE_B(y,z), TYPE_C(b,s) private boolean incremental; //has get/set private String someStr; //has get/set ExecutionMode(boolean incremental,String someStr){ ///... set things appropriately } } 

If you set these values ​​at runtime, my tendency will be that this should not be an enumeration in the first place - there should be a separate POJO, which may contain values, as well as a link to the enumeration value.

+7
source

From the Java language specification :

The latest cloning method in Enum ensures that enumeration constants will never be cloned and special processing by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization . Reflective creation of enumeration types is prohibited. Together, these four things ensure that no instances of the enumeration type exist beyond the limits defined by the enumeration constants.

What you ask for would create more than one instance of, say, TYPE_A. This will break the listings. Enumerations must be unchanged.

+5
source

All Articles