为什么我必须在以下代码中显式地将命令强制转换为 C? Commands 实现了 Runnable 和 Describable。
@Test
public <C extends Runnable & Describable> void testMapOfCommands() throws Exception
{
Map<String, C> commands = Maps.newHashMap();
for(Commands command : Commands.values())
{
commands.put(command.name(), (C) command);
}
//Use commands here (not relevant to my question):
//CommandLineParser.withCommands(commands).parse("commit");
}
private enum Commands implements Runnable, Describable
{
commit
{
@Override
public void run()
{
System.out.println("COMMIT");
}
@Override
public String description()
{
return "Commits something";
}
};
}
我想到的一个解决方法是引入扩展 Runnable 和 Describable 的 ICommand:
public interface ICommand extends Runnable, Describable{}
但是当已经有两种可用的类型并且我已经有一个稍微复杂一点的 Command 类时,我试图避免引入新类型。我是不是在抓救命稻草?
最佳答案
你有一个 command
Commands
类型的对象.但是因为你的泛型类型声明 <C extends Runnable & Describable>
, Java 期望 C
两者都是 Describable
和 Runnable
,但是 C
不一定是 Commands
.
这种特殊的测试方法不适用于 Commands
以外的任何东西,所以它不应该是通用的。这应该有效:
public void testMapOfCommands() throws Exception
{
Map<String, Commands> commands = new HashMap<String, Commands>();
for(Commands command : Commands.values())
{
commands.put(command.name(), command);
}
}
关于java - 声明具有两个接口(interface)的泛型类型参数时如何避免不必要的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16179940/