结合java枚举和泛型

uemypmqf  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(380)

我正在尝试使用泛型和枚举设计一段代码。我希望得到枚举使用原始整数以及它必须持有一个字符串。我有很多枚举,所以我用一个接口实现了它们,以便记住重写公共 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];
}
whlutmcx

whlutmcx1#

试试这个:

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() 在接口中是没有意义的。)

相关问题