为什么这种类型不能替代类型参数?

for*_*two 10 java generics

我正在尝试使用泛型来支持委托对象(装饰器,包装器)的可配置结构.我想构建一个实现目标接口和通用委托接口的委托链.

我有这个大纲:

class Test {
    static interface Delegator<T> {}

    static class DelegatorChain<T extends Delegator<T>> {}

    static interface Foo {}

    static class FooDelegator implements Delegator<Foo>, Foo {}

    public static void main(String[] args) {
        DelegatorChain<FooDelegator> chain = new DelegatorChain<FooDelegator>();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,在尝试实例化chain变量时,编译器抱怨:

绑定不匹配:类型Test.FooDelegator不是该类型的有界参数<T extends Test.Delegator<T>>的有效替代Test.DelegatorChain<T>

我承认泛型对我来说就像魔术一样,但我可以以某种方式承认FooDelegator不是扩展 Delegator <Foo>的Foo,它只是实现了两个接口.

鉴于我很清楚我想要完成什么,有什么我可以用gertics来修复它,或者我只是更好地忘记了它?

Boh*_*ian 9

根据您的定义,Delegator本身就是一个Delegator(例如Comparable),但似乎意图是Delegator是超类的Delegator.幸运的是,泛型有一种表达方式:

static class DelegatorChain<T extends Delegator<? super T>> {}
Run Code Online (Sandbox Code Playgroud)

这表示"Delagator类型必须是T的超类".通过此更改,原始代码的其余部分将编译:

static interface Delegator<T> {}
static class DelegatorChain<T extends Delegator<? super T>> {}
static interface Foo {}
static class FooDelegator implements Delegator<Foo>, Foo {}

public static void main(String[] args) {
    DelegatorChain<FooDelegator> chain = new DelegatorChain<FooDelegator>();
}
Run Code Online (Sandbox Code Playgroud)

此外,无论何时使用通用超级绑定,您的代码看起来都非常酷:)



注意:以下内容最初是问题中的"第一个选项".
还有另一种方法可以让您的代码进行编译,但它是次要的,因为它失去了Delegator类型与委托代理之间的连接:

// Not recommended, but will allow compile:
static class FooDelegator implements Delegator<FooDelegator>, Foo {} 
// However, this also compiles :(
static class FooDelegator implements Delegator<FooDelegator>, Bar {} 
Run Code Online (Sandbox Code Playgroud)