6

サブクラスの型の型パラメーターを使用してThingへの参照を取得するなど、いくつかの基本機能を提供する基本クラスがあります。Java には自己型がないため、型パラメーターを戻り値に使用することはできません。そのため、再帰型パラメーターを使用して、正しいパラメーター化された .ThingInfoThingThingInfoThingThingInfo

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の引数を取るメソッドが必要です。そこで、次のように変更します。ThingRelationYThingThingRelation

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.

4

1 に答える 1

0

あなたの正確なコード(jdk1.6.0_20を使用)でエラーは発生しません。

シャドウされた型変数を持っている可能性がありますか? あなたは明らかにあなたの例を単純なクラス名に編集しました(Thingなど、これは良い仕事でした)が、意図した以上に編集した可能性があります。YおよびX型の宣言については、ソース コードを確認してください。

于 2012-08-19T18:59:13.583 に答える