gpt4 book ai didi

具有递归类型参数的 Java 泛型边界

转载 作者:搜寻专家 更新时间:2023-10-31 08:04:01 25 4
gpt4 key购买 nike

我有一个基类 Thing ,它提供了一些基本功能,包括获取对 ThingInfo 的引用使用 Thing 类型的类型参数子类。因为 Java 没有自身类型,所以我不能将其用于 ThingInfo 的类型参数。返回值,所以 Thing必须采用递归类型参数以允许我们返回正确的参数化 ThingInfo .

interface ThingInfo<T>
{
// just an example method showing that ThingInfo needs to know about
// the type parameter T
T getThing();
}

class Thing<T extends Thing<T>>
{
// I need to be able to return a ThingInfo with the type parameter
// of the sub class of Thing. ie. ThingA.getThingInfo() must return
// a ThingInfo<ThingA>.
// This is where Java would benefit from self types, as I could declare
// the method something like: ThingInfo<THIS_TYPE> getThingInfo()
// and Thing would not need a type parameter.
ThingInfo<T> getThingInfo()
{
return something;
}
}

// example Thing implementation
class ThingA extends Thing<ThingA>
{
}

// example Thing implementation
class ThingB extends Thing<ThingB>
{
}

目前一切正常。此代码根据需要工作。

我还需要表示 Thing 之间的类型安全关系

class ThingRelation<X extends Thing<X>, Y extends Thing<Y>>
{
X getParent()
{
return something;
}

Y getChild()
{
return something;
}
}

它并没有那么简单,但这证明了我认为的必要性。尽管如此,这一切都很好,还没有错误。现在,ThingRelation需要采用 ThingRelation 参数的方法在 Y 之间和其他一些Thing .所以我改变ThingRelation到以下内容:

class ThingRelation<X extends Thing<X>, Y extends Thing<Y>>
{
X getParent()
{
return something;
}

Y getChild()
{
return something;
}

<Z extends Thing<Z>> void useRelation(ThingRelation<Y, Z> relation)
{
// do something;
}
}

但是现在我在编译的时候遇到了这个错误:

type argument Y is not within bounds of type-variable X
where Y,X are type-variables:
Y extends Thing<Y> declared in class ThingRelation
X extends Thing<X> declared in class ThingRelation

错误在开始 <Z extends Thing<Z>>.... 的行上

到底是什么问题?

更新:javac版本是 1.7.0_05 .

最佳答案

您的确切代码(使用 jdk1.6.0_20)我没有发现任何错误。

会不会是你有一个阴影类型变量?您显然已经将您的示例编辑为简单的类名(Thing 等,顺便说一句,这是很好的工作),但也许您编辑的内容超出了您的预期。检查源代码中是否有 YX 类型的声明。

关于具有递归类型参数的 Java 泛型边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12029042/

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