我想创建一个方法,它通过它的值返回枚举常量。
我有多个枚举类,它们看起来像这样(其中一些具有不同名称的 getter 变量):
@AllArgsConstructor
public enum PhoneType {
MOBILE("Mobile", 3),
HOME("Home", 6),
WORK("Work", 7);
@Getter
String type;
@Getter
int id;
}
Run Code Online (Sandbox Code Playgroud)
我使用这个流来获取枚举常量:
int phoneTypeId = 3;
PhoneType phoneType = Arrays.stream(PhoneType.values())
.filter(p -> p.getId() == phoneTypeId)
.findFirst()
.orElseThrow(() -> new RuntimeException("Not able to find Enum...."));
System.out.println(phoneType.getType());
Run Code Online (Sandbox Code Playgroud)
输出为:“移动”
现在我想创建一个适用于不同枚举类的方法。我从这样的事情开始,但我不知道如何重写过滤器行,使其适用于任何枚举类。最好将此“p -> p.getId() == phoneTypeId”作为输入参数传递给此方法。有任何想法吗?
public static <E extends Enum<?>> E getEnumByValue(Class<E> enumClass) {
return Arrays.stream(enumClass.getEnumConstants())
.filter(p -> p.getId() == phoneTypeId)
.findFirst()
.orElseThrow(() -> new RuntimeException("Not able to find Enum...."));
}
Run Code Online (Sandbox Code Playgroud)
(我知道如果我为所有枚举类实现接口,则可以这样做,但是枚举变量必须具有相同的名称。)
你可以把它作为一个Predicate:
public static <E extends Enum<?>> Optional<E> getEnumByValue(Class<E> enumClass, Predicate<E> predicate) {
return Arrays.stream(enumClass.getEnumConstants())
.filter(predicate)
.findFirst();
}
Run Code Online (Sandbox Code Playgroud)
(注意:该方法实际上应该返回一个Optional<E>)
如果所有枚举都有 id,您仍然可以实现一个通用接口:
interface Identifiable {
int getId();
}
enum PhoneType implements Identifiable {
...
}
public static <E extends Enum<?> & Identifiable> Optional<E> getEnumById(Class<E> enumClass, int id) {
return Arrays.stream(enumClass.getEnumConstants())
.filter(e -> e.getId() == id)
.findFirst();
}
Optional<PhoneType> phone = getEnumById(PhoneType.class, phoneTypeId);
Run Code Online (Sandbox Code Playgroud)