我有一个基类Thing
,它提供了一些基本功能,包括获取对具有Thing
子类类型的类型参数的ThingInfo
的引用。因为 Java 没有 self 类型,所以我不能将其用于 type 参数到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
需要方法,该方法在Y
和其他一些Thing
之间接受ThingRelation
的参数。所以我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
等,顺便说一句,这是一个很好的工作),但也许您编辑的比预期的要多。检查源代码中是否有 Y
和X
类型的声明。