我正在尝试在以我自己的 Enum 作为参数的抽象类中创建一个抽象方法。但我也希望 Enum 是通用的。
所以我这样声明:
public abstract <T extends Enum<T>> void test(Enum<T> command);
在实现中,我将枚举作为那个:
public enum PerspectiveCommands {
PERSPECTIVE
}
方法声明变为:
@Override
public <PerspectiveCommands extends Enum<PerspectiveCommands>> void test(Enum<PerspectiveCommands> command) {
}
但如果我这样做:
@Override
public <PerspectiveCommands extends Enum<PerspectiveCommands>> void test(Enum<PerspectiveCommands> command) {
if(command == PerspectiveCommands.PERSPECTIVE){
//do something
}
}
我无法访问 PerspectiveCommands.PERSPECTIVE
并出现错误:
cannot find symbol symbol: variable PERSPECTIVE location: class Enum<PerspectiveCommands> where PerspectiveCommands is a type-variable: PerspectiveCommands extends Enum<PerspectiveCommands> declared in method <PerspectiveCommands>test(Enum<PerspectiveCommands>)
我做了一个这样的解决方法:
public <T extends Enum<T>> byte[] executeCommand(Enum<T> 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)或抽象类。所以尝试这样的事情:
interface TestInterface<T extends Enum<T>>
{
public abstract void test(T command);
}
class TestImpl implements TestInterface<PerspectiveCommands>
{
@Override
public void test(PerspectiveCommands command) {
if(command == PerspectiveCommands.PERSPECTIVE){
//do something
}
}
}
关于Java Enum 作为 Enum 中的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18738133/