gpt4 book ai didi

java - 为什么此类型不是类型参数的有效替代品?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:55:13 24 4
gpt4 key购买 nike

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

我有这个大纲:

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>();
}
}

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

Bound mismatch: The type Test.FooDelegator is not a valid substitute for the bounded parameter <T
extends Test.Delegator<T>>
of the type Test.DelegatorChain<T>

我承认泛型就像magic对我来说,但我可以以某种方式承认 FooDelegator 不是 extends Delegator 的 Foo,它只是实现了两个接口(interface)。

鉴于我想完成的事情很明确,有什么我可以做的吗?泛型来修复它,还是我最好忘记它?

最佳答案

根据您的定义,委托(delegate)人是其自身的委托(delegate)人(例如 Comparable),但似乎意图是委托(delegate)人是父类(super class)的委托(delegate)人。幸运的是,泛型有一种表达方式:

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

这表示“Delagator 类型必须是 T 的父类(super class)”。通过此更改,您的原始代码的其余部分可以编译:

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>();
}

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



注:下面这个原本是题中的“第一个选项”。
还有另一种方法可以让你的代码编译,但它是次等的,因为它失去了委托(delegate)类型和它委托(delegate)的对象之间的联系:

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

关于java - 为什么此类型不是类型参数的有效替代品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7032941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com