如何让两个枚举关联起来

在开发过程中,发现其他服务调用我们的服务,这是很常见的问题。比如,我们定义了一个设备类型,这个枚举是在我们系统中使用的,但是和其他系统交互,其他系统有其他系统的设备类型。我们是不一致的。怎么解决呢?

我们的设备类型枚举:

@Getter
@AllArgsConstructor
public enum DeviceType {
	A(1, "A"),
	B(2, "B"),
	;

	/** 标记响应数据库的值 **/
	@EnumValue
	/** 标记响应json值(序列化) **/
	@JsonValue
	private final int index;
	private final String name;

	private static Map<Integer, DeviceType > map = Maps.newHashMap();

	static {
		for (DeviceType e : DeviceType.values()) {
			map.put(e.getIndex(), e);
		}
	}

	/**
	 * 反序列化时初始化(入参为 对应该枚举的 @JsonValue值)
	 */
	@Nullable
	@JsonCreator(mode = Mode.DELEGATING)
	public static DeviceType of(Integer index) {
		return map.get(index);
	}

	
}

new了一个其他系统的设备枚举:

@Getter
@AllArgsConstructor
public enum OtherDeviceType {

	D(0, DeviceType.A.getIndex()),
	E(1, DeviceType.B.getIndex()),
	;

	/** 标记响应数据库的值 **/
	@EnumValue
	/** 标记响应json值(序列化) **/
	@JsonValue
	private final int index;
	private final int deviceTypeIndex;

	private static Map<Integer, OtherDeviceType> map = Maps.newHashMap();

	static {
		for (OtherDeviceType e : OtherDeviceType.values()) {
			map.put(e.getIndex(), e);
		}
	}

	/**
	 * 反序列化时初始化(入参为 对应该枚举的 @JsonValue值)
	 */
	@Nullable
	@JsonCreator(mode = Mode.DELEGATING)
	public static OtherDeviceType of(Integer index) {
		return map.get(index);
	}

}

创建好这两个枚举之后,我们在代码中是如何处理的呢?

当我们接收到其他系统发过来的类型之后,我们先做类型转换,这样我们会拿到其他类型设备的枚举对象,那么我们再通过我们自己的设备类型进行获取:

OtherDeviceType otherDeviceType = OtherDeviceType.of(otherDeviceType);
DeviceType deviceType = DeviceType.of(otherDeviceType.getDeviceTypeIndex());

相当于类型转换了两次,只是我们在声明枚举的时候,把这两个关联起来。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值