Custom fields on java enum not getting serialized

可紊 提交于 2019-12-19 06:39:07

问题


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 custom fields on the enum are lost. On reading more about it, I got the impression that enum gets deserialized into a string and hence its custom fields are ignored.

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

Thanks!


回答1:


If the values are constant, this is better and you don't 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're setting these values at runtime, my inclination would be that this shouldn't be an enum in the first place - there should be a separate POJO that perhaps contains the values as well as a reference to an enum value.




回答2:


From the Java language specification:

The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.

What you are asking for would create more than one instance of, say, TYPE_A. This would break enums. Enums should be immutable.



来源:https://stackoverflow.com/questions/15529490/custom-fields-on-java-enum-not-getting-serialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!