为什么这种类型不能替代类型参数?
我正在尝试使用generics来支持委托对象(装饰器,包装器)的可配置结构。 我想构建一个委托链,它实现了一个目标接口以及一个通用委托接口。
我有这个大纲:
class Test { static interface Delegator {} static class DelegatorChain<T extends Delegator> {} static interface Foo {} static class FooDelegator implements Delegator, Foo {} public static void main(String[] args) { DelegatorChain chain = new DelegatorChain(); } }
但是,当试图实例化chain
变量时,编译器抱怨:
绑定不匹配:类型Test.FooDelegator不是有效参数的有效替代
<T extends Test.Delegator>
,类型为Test.DelegatorChain
我承认generics对我来说就像魔术一样,但我可以以某种方式承认FooDelegator不是扩展 Delegator 的Foo,它只是实现了两个接口。
鉴于我很清楚我想要完成什么,是否有什么我可以用gertics来解决它,或者我只是更好地忘记了它?
根据您的定义,Delegator本身就是一个委托人(例如Comparable),但似乎意图是Delegator是超类的委托人。 幸运的是,generics有一种表达方式:
static class DelegatorChain> {}
这表示“Delagator类型必须是T的超类”。 通过此更改,原始代码的其余部分将编译:
static interface Delegator {} static class DelegatorChain > {} static interface Foo {} static class FooDelegator implements Delegator, Foo {} public static void main(String[] args) { DelegatorChain chain = new DelegatorChain (); }
此外,无论何时使用通用超级绑定,您的代码看起来都非常酷:)
注意:以下内容最初是问题中的“第一个选项”。
还有另一种方法可以让您的代码进行编译,但它是次要的,因为它失去了Delegator类型与委托代理之间的连接:
// Not recommended, but will allow compile: static class FooDelegator implements Delegator, Foo {} // However, this also compiles :( static class FooDelegator implements Delegator , Bar {}
看起来这就是你想要做的事情。
static interface Delegator { } static class DelegatorChain , C> { } static interface Foo { } static class FooDelegator implements Delegator, Foo { } public static void main(String[] args) { DelegatorChain chain = new DelegatorChain(); }
您的初始示例无法编译,因为类型不正确。 DelegatorChain中的Generic类型是“FooDelegator”,但Delegator中所需的generics类型是“Foo”。 您需要我在答案中提供的额外generics类型参数,以使其按预期工作。
您也可以将约束完全保留在DelegatorChain即DelegatorChain上。
如果FooDelegator implements Delegator
或者Foo implements Delegator
FooDelegator implements Delegator
Foo implements Delegator
,那么应FooDelegator implements Delegator
? 因为这是DelegatorChain所要求的: T implements Delegator
。
第三种选择,也应该有效:
DelegatorChain, F> chain; ...