Java通用枚举function使用java 8默认方法和实用程序类

下面是我提出的失败尝试,指的是使用Reflection的Java Generic Enum类 。

想找到一个更好的方法来做到这一点。 我用这种方法找到了几个问题:

  • 每次我都需要传递类类型。 示例 – EnumUtility.fromKey(Country.class,1)

  • fromSet在城市和国家都重复

public enum City implements BaseEnumInterface { TOKYO(0), NEWYORK(1); private final int key; public static Set fromValue(Set enums) { return enums.stream().map(City::getKey).collect(Collectors.toSet()); } public int getKey() { return key; } private City(int key) { this.key = key; } } public enum Country implements BaseEnumInterface { USA(0), UK(1); private final int key; public static Set fromSet(Set enums) { return enums.stream().map(Country::getKey).collect(Collectors.toSet()); } public int getKey() { return key; } private Country(int key) { this.key = key; } } public class EnumUtility { public static <E extends Enum & BaseEnumInterface> E fromKey(Class enumClass, Integer key) { for (E type : enumClass.getEnumConstants()) { if (key == type.getKey()) { return type; } } throw new IllegalArgumentException("Invalid enum type supplied"); } public static <E extends Enum & BaseEnumInterface> Set fromSet(Class enumClass, Set enums) { return enums.stream().map(BaseEnumInterface::getKey).collect(Collectors.toSet()); } } interface BaseEnumInterface { int getKey(); } public class EnumTester { public static void main(String args[]) { System.out.println(EnumUtility.fromKey(Country.class, 1)); } } 

没有办法避免将枚举类传递给fromKey。 你怎么知道哪个枚举常量检查所请求的密钥? 注意:该方法中的第二个参数应为int类型,而不是Integer。 在整数实例上使用==将不会比较数值,它将比较对象引用!

EnumUtility.fromSet应该可以正常工作,因此每个枚举类根本不需要fromSet方法。 请注意,EnumUtility.fromSet根本不需要Class参数,实际上您的代码不使用该参数。