Java Enum作为Enum中的generics类型
我正在尝试在抽象类中创建一个抽象方法,该方法将我自己的Enum作为参数。 但我也希望Enum是通用的。
所以我宣布它是这样的:
public abstract <T extends Enum> void test(Enum command);
在实现中,我已经知道了那个:
public enum PerspectiveCommands { PERSPECTIVE }
并且方法声明变为:
@Override public <PerspectiveCommands extends Enum> void test(Enum command) { }
但如果我这样做:
@Override public <PerspectiveCommands extends Enum> void test(Enum command) { if(command == PerspectiveCommands.PERSPECTIVE){ //do something } }
我没有访问带有错误的PerspectiveCommands.PERSPECTIVE
:
cannot find symbol symbol: variable PERSPECTIVE location: class Enum where PerspectiveCommands is a type-variable: PerspectiveCommands extends Enum declared in method test(Enum)
我做了一个像这样的解决方法:
public <T extends Enum> byte[] executeCommand(Enum command) throws Exception{ return executeCommand(command.name()); } @Override protected byte[] executeCommand(String e) throws Exception{ switch(PerspectiveCommands.valueOf(e)){ case PERSPECTIVE: return executeCommand(getPerspectiveCommandArray()); default: return null; } }
但我想知道是否有可能不通过我的解决方法?
在您的方法实现中, PerspectiveCommands
不是枚举,而是您的类型参数,通常称为T
因此它像axtavt已经说过的那样影响了同名的枚举,因此这里的PERSPECTIVE
是未知的。
您的抽象方法声明很好,但您可能会使用稍微不同的方法。
public void test(PerspectiveCommands command)
不起作用,因为此方法不会覆盖通用版本。 原因是通用版本的类型是从参数推断的,因此您可以传递任何枚举。
但是,我假设您有一个定义抽象方法的接口或抽象类。 所以尝试这样的事情:
interface TestInterface> { public abstract void test(T command); } class TestImpl implements TestInterface { @Override public void test(PerspectiveCommands command) { if(command == PerspectiveCommands.PERSPECTIVE){ //do something } } }
@迈克的答案是要走的路。
public interface Command1 { } public enum MyCommand1 implements Command1 { } abstract & Command1> void execute(E command);
这是另一个版本
// intending to be used only on enums public interface Command2> extends Command1 { } public enum MyCommand2 implements Command2 { } abstract & Command2 > execute(E command);
正如@axtavt已经指出的那样,问题就是影子。
如果希望代码按原样运行,可以更改类型变量的名称以删除阴影。
public > void test(Enum command)
我还要为类型边界添加一个接口,只允许命令枚举,而不是每个枚举派生类的实例。
public & CommandInterface> void test(Enum command)