在开发过程中,发现其他服务调用我们的服务,这是很常见的问题。比如,我们定义了一个设备类型,这个枚举是在我们系统中使用的,但是和其他系统交互,其他系统有其他系统的设备类型。我们是不一致的。怎么解决呢?
我们的设备类型枚举:
@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());
相当于类型转换了两次,只是我们在声明枚举的时候,把这两个关联起来。