java枚举序列化,java枚举上的自定义字段未被序列化

本文讨论了在Java中使用枚举时,如何避免在反序列化后丢失自定义字段的问题。作者提供了两种解决方案,一种是常量模式,另一种是针对运行时设置值的情况。讨论了何时选择POJO而非枚举,以及如何正确处理枚举的定制属性。
摘要由CSDN通过智能技术生成

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值