2017-09-04 69 views
2

我想用泛型和枚举设计一段代码。我希望使用原始整数来获得枚举,并且它必须包含一个字符串。我有很多枚举,所以我通过一个接口实现它们,以便记住覆盖公共方法toString()getIndex()getEnum()。然而,我正在得到一个类型安全警告,任何想法如何摆脱它,以及为什么发生?结合Java枚举和泛型

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]; 
} 
+0

仅供参考,宣布'的toString()'在界面也没用。所有的'对象'已经声明。你所需要做的就是在实现类中覆盖它。 – ajb

回答

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

+0

谢谢,你能解释一下它是如何摆脱警告的吗? – user2609825

+0

我认为这是因为在我的代码中,当你说'ENUM_A implements EnumInf '时,编译器可以在那里发现'T'与'ENUM_A'相同,所以方法的返回类型是相同的。在你的原始代码中,显然它没有足够的信息来解决这个问题。也许这是因为实现方法的返回类型不必与接口方法相同,因为协方差。但我确实不知道。 – ajb

+0

你正在使用原始类型 – newacct