【发布时间】:2020-10-20 21:55:55
【问题描述】:
我正在为如下所示的命令外壳编写代码:
interface Context<C extends Context<C>> {}
interface RecursiveContext<C extends RecursiveContext<C>> extends Context<C> {
Shell<C> getShell();
default Result execute(Command cmd) { return getShell().execute(cmd, this); }
}
interface Shell<C extends Context<C>> {
C newContext();
Result execute(Command cmd, C context);
}
我在默认方法中遇到错误提示
The method execute(Command, C) in the type Shell<C> is not applicable for the arguments (Command, RecursiveContext<C>)
我希望这会起作用,因为Shell<C> getShell() 保证能够在其execute 调用中接受C,并且因为this 实际上保证是相同自绑定类型的子类型C,但编译器似乎不同意我的看法。不匹配在哪里,在默认方法中执行强制转换是否安全?如果这不安全,你能提供一个类型不匹配的反例吗?
我也尝试在 shell <D extends C> execute(Command, D) 中引入一个中间类型,但这似乎没有任何改变。
(大多数建议的问题都涉及原始类型的中间步骤,但我认为我没有错过。)
【问题讨论】: