结合Java Enum和Generics

时间:2017-09-04 02:49:13

标签: java generics enums

我正在尝试使用泛型和枚举设计一段代码。我希望使用原始整数获取枚举,并且它必须包含字符串。我有很多枚举,因此我使用界面实现它们,以便记住覆盖公共toString()getIndex()getEnum()方法。但是,我得到了一个类型安全警告,任何想法如何摆脱它以及它为什么会发生?

public interface EnumInf{
    public String toString();
    public int getIndex();
    public <T> T getEnum(int index);
}

public enum ENUM_A implements EnumInf{
    E_ZERO(0, "zero"),
    E_ONE(1, "one"),
    E_TWO(2, "two");

private int index;
private String name;
private ENUM_A(int _index, String _name){
    this.index = _index;
    this.name = _name;
}
public int getIndex(){
    return index;
}
public String toString(){
    return name;
}
// warning on the return type:
// Type safety:The return type ENUM_A for getEnum(int) from the type  ENUM_A needs unchecked conversion to conform to T from the type EnumInf
public ENUM_A getEnum(int index){
    return values()[index];
}

1 个答案:

答案 0 :(得分:3)

试试这个:

public interface EnumInf<T extends EnumInf<T>> {
    public int getIndex();
    public T getEnum(int index);
}

public enum ENUM_A implements EnumInf<ENUM_A> {
    ... the rest of your code

(正如我在评论中指出的那样,在界面中声明toString()毫无意义。)