在对外暴露接口时,如果以枚举作为入参,应该对调用者传入的字符串是否为枚举类中的成员进行判断,可以在枚举类中增加一个contains方法进行校验:
public static boolean containsKey(String key) {
return Arrays.stream(KeyEnum.values())
.map(KeyEnum::getKey)
.distinct().anyMatch(s -> Objects.equals(s, key));
}
public static boolean contains(String type){
for(TypeEnum typeEnum : TypeEnum.values()){
if(typeEnum.name().equals(type)){
return true;
}
}
return false;
}