当枚举类多了之后,会存在很多重复的值和描述相互转化的方法,类似getEnmuByValue和getEnmuByKey。
最近找到一种方法,利用接口、接口默认方法、泛型,实现通用的方法。同类型的枚举只需要实现该接口即可。
public interface ICommonEnum {
int getValue();
String getKey();
static <E extends Enum<E> & ICommonEnum> E getEnmu(Integer value, Class<E> clazz) {
Objects.requireNonNull(value);
EnumSet<E> all = EnumSet.allOf(clazz);
return all.stream().filter(e -> e.getValue() == value).findFirst().orElse(null);
}
static <E extends Enum<E> & ICommonEnum> E getEnmu(String key, Class<E> clazz) {
Objects.requireNonNull(key);
EnumSet<E> all = EnumSet.allOf(clazz);
return all.stream().filter(e -> e.getKey().equals(key)).findFirst().orElse(null);
}
}
具体用法:
public enum RtuProtocol implements ICommonEnum {
PTL_A(1, "A规约"), PTL_B(2, "B规约");
private int value;
private String key;
RtuProtocol(int value, String key) {
this.value = value;
this.key = key;
}
public int getValue() {
return value;
}
public String getKey() {
return key;
}
}
转换时的调用举例:
RtuProtocol protocol = ICommonEnum.getEnmu(1,RtuProtocol.class)