【问题标题】:Java generic enum functionality using java 8 default methods and utility class使用 java 8 默认方法和实用程序类的 Java 通用枚举功能
【发布时间】:2017-10-09 06:37:04
【问题描述】:

以下是我想出的失败尝试,指的是Java Generic Enum class using Reflection

想找到一种更好的方法来做到这一点。我发现这种方法存在几个问题:

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

  • fromSet 在城市和国家/地区都重复

public enum City implements BaseEnumInterface {

    TOKYO(0), NEWYORK(1);

    private final int key;

    public static Set<Integer> fromValue(Set<City> 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<Integer> fromSet(Set<Country> 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<E> & BaseEnumInterface> E fromKey(Class<E> 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<E> & BaseEnumInterface> Set<Integer> fromSet(Class<E> enumClass, Set<E> 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));
    }
}

【问题讨论】:

  • 那为什么你的enums又实现了一个接口呢?

标签: java generics enums interface java-8


【解决方案1】:

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

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

【讨论】:

  • 好的,每个类 City 和 Country 中的 fromValue 怎么样?我可以避免重复吗?
  • City.fromValue 和 Country.fromSet 是相同的。当我提到每个枚举类的 fromSet 方法时,我指的是 City.fromValue 和 Country.fromSet。这两种方法都不需要。
  • 不仅Class 参数已过时。你可以像public static Set&lt;Integer&gt; fromSet(Set&lt;? extends BaseEnumInterface&gt; enums) { return enums.stream() .map(BaseEnumInterface::getKey) .collect(Collectors.toSet()); } 那样简单,它将接受任何一组BaseEnumInterface 子类型,即Set&lt;City&gt;Set&lt;Country&gt;,它们是否是enum 类型甚至都无关紧要……
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
  • 2017-10-01
  • 2011-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多