java枚举上的自定义字段未被序列化 [英] Custom fields on java enum not getting serialized

查看:425
本文介绍了java枚举上的自定义字段未被序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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; //有get / set
}

我看到,在反序列化之后,枚举丢失。
在阅读更多关于它的时候,我得到的印象是,枚举被反序列化成一个字符串,因此它的自定义字段被忽略。



如果它是真的,我是Enum这里滥用应该用POJO istead吗?
还是有办法序列化自定义字段(不是构造函数的一部分)?



谢谢!

解决方案

如果值是不变的,这是更好的,你不需要序列化任何

  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){
/// ...正确设置东西
}
}

如果您在运行时设置这些值,我的倾向是,这不应该是第一个枚举地方 - 应该有一个单独的POJO,可能包含值和引用枚举值。


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!

解决方案

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.

这篇关于java枚举上的自定义字段未被序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆