在我的项目中,一个共同的愿望是在给定其构造值之一的情况下找到一个枚举.例如:
public enum Animal {
DOG("bark"),
CAT("meow");
public final String sound;
Animal(String sound) {
this.sound = sound;
}
public String getSound() {
return sound;
}
}
如果给出字符串"meow"
,我想得到CAT
简单的解决方案是编写一个遍历Enum的值的搜索方法
public static Animal getBySound(String sound) {
for(Animal e : values()){
if(e.sound.equals(sound)){
return e;
}
}
}
但这必须单独完成,对于定义的每个枚举.Is there a way, given an Enum class and a method that gets a field's value, you can get the enum who's specified field matches the input?个
可能的签名:
public static <T extends Enum<T>, V> Optional<T> findEnumByValue(Class<T> enumClass, Function<T, V> fieldGetter, V valueToMatch)
我得到的最接近的结果是这样,但是将第一个参数设置为Enum[]
距离完全类型安全只有一步之遥(因为该方法可以提供任意的枚举数组)
public static <T extends Enum<T>, V> Optional<T> findEnumByValue(T[] enums, Function<T, V> fieldGetter, V valueMatch) {
return Arrays.stream(enums).filter(element -> Objects.equals(fieldGetter.apply(element), valueMatch)).findFirst();
}
// Example usage
Animal animal = findEnumByValue(Animal.values(), Animal::getSound, "meow").orElse(CAT);
似乎部分困难在于作 for each Enum类的一部分的静态方法values()
不能通过Class
对象访问.