Jes*_*sse 6 java generics javac java-7
我有一个基类Thing,它提供了一些基本功能,包括ThingInfo使用类的类型参数获取对a的引用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>
{
}
Run Code Online (Sandbox Code Playgroud)
到目前为止一切都很好.此代码可根据需要运行.
我还需要表示Things 之间的类型安全关系.
class ThingRelation<X extends Thing<X>, Y extends Thing<Y>>
{
X getParent()
{
return something;
}
Y getChild()
{
return something;
}
}
Run Code Online (Sandbox Code Playgroud)
它不是那么简单,但这表明了我的需要.尽管如此,所有这一切都很好,没有错误.现在,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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是现在我在编译时遇到了这个错误:
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
Run Code Online (Sandbox Code Playgroud)
错误在线上开始 <Z extends Thing<Z>>....
究竟是什么问题呢?
更新:javac版本是1.7.0_05.
我的确切代码没有错误(使用 jdk1.6.0_20)。
难道你有一个隐藏类型变量?显然,您已经将示例编辑为简单的类名(Thing等等,顺便说一句,这是一项很好的工作),但也许您编辑的内容超出了您的预期。检查源代码中的声明Y和X类型。
| 归档时间: |
|
| 查看次数: |
1545 次 |
| 最近记录: |