サブクラスの型の型パラメーターを使用してThing
への参照を取得するなど、いくつかの基本機能を提供する基本クラスがあります。Java には自己型がないため、型パラメーターを戻り値に使用することはできません。そのため、再帰型パラメーターを使用して、正しいパラメーター化された .ThingInfo
Thing
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>
{
}
これまでのところ、すべて問題ありません。このコードは必要に応じて機能します。
また、s 間のタイプ セーフな関係を表す必要もありThing
ます。
class ThingRelation<X extends Thing<X>, Y extends Thing<Y>>
{
X getParent()
{
return something;
}
Y getChild()
{
return something;
}
}
それほど単純ではありませんが、それは私が考える必要性を示しています。それでも、これはすべて問題なく、まだエラーはありません。ここで、 betweenと otherThingRelation
の引数を取るメソッドが必要です。そこで、次のように変更します。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
.