Enum定义最佳实践

2021-08-06  本文已影响0人  xin_5457

Enum 在 jackson 序列化和反序列化时默认使用枚举的name(), 而一般存储的数据可能是自定义字段。可以通过一下方法改进。

public enum UserAgentEnum {
 
    IOS(1, "IOS"),
    ANDROID(2, "ANDROID"),
    WXSP(3, "微信小程序"),
    PC(4, "PC"),
    H5(5, "H5");
 
    @JsonValue
    @Getter
    private final int code;
 
    @Getter
    private final String description;
 
    UserAgentEnum(int code, String description) {
        this.code = code;
        this.description = description;
    }
 
    private static final Map<Integer, UserAgentEnum> VALUES = new HashMap<>();
 
    static {
        for (final UserAgentEnum userAgent : UserAgentEnum.values()) {
            UserAgentEnum.VALUES.put(userAgent.getCode(), userAgent);
        }
    }
 
    @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
    public static UserAgentEnum of(int code) {
        return UserAgentEnum.VALUES.get(code);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读