通用方法参数:实现接口的枚举

fan*_*cco 2 java generics enums

我有一个interface:

public interface NamedEnum {
    String getName();
}
Run Code Online (Sandbox Code Playgroud)

一个enum实现interface:

public enum MyEnum implements NamedEnum {

    MYVALUE1("My value one"),
    MYVALUE2("My value two");

    private String name;

    private MyEnum(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
Run Code Online (Sandbox Code Playgroud)

一种不编译的方法:

public static Map<Integer,String> wrong(Enum<? extends NamedEnum> value) {
    Map<Integer,String> result = new LinkedHashMap<Integer, String>();
    for (Enum<? extends NamedEnum> val : value.values())
        result.put(val.ordinal(), val.getName());
    return result;
}
Run Code Online (Sandbox Code Playgroud)

两个错误:

The method values() is undefined for the type Enum<capture#1-of ? extends NamedEnum> The method getName() is undefined for the type Enum<capture#3-of ? extends NamedEnum>

我无法弄清楚上面的方法如何接受enum实现的方法interface.

And*_*ner 7

使用交集类型定义类型变量:

public static <E extends Enum<E> & NamedEnum> Map<Integer,String> wrong(E value) {
Run Code Online (Sandbox Code Playgroud)

但请注意,这是传递枚举的一个元素,而不是枚举类本身.您可能想要使用:

public static <E extends Enum<E> & NamedEnum> Map<Integer,String> wrong(Class<E> clazz) {
Run Code Online (Sandbox Code Playgroud)

然后使用clazz.getEnumConstants()获取迭代的值:

for (E val : clazz.getEnumConstants())
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用value.getDeclaringClass().getEnumConstants().