私は自分のプロジェクトの1つに一般性を追加することになっています。ジェネリックスが大好きです。これにより、コードがより堅牢になり、自己文書化され、醜いキャストがすべて消去されます。
しかし、私は困難なケースに遭遇し、私の構造の1つに「再帰的」制約を表現しようとしていくつかの問題が発生しました。
これは基本的に、(子と親への)二重リンクを持つある種の「一般的な」ツリーです。問題を示すために、クラスを最大で簡略化しました。
public class GenericTree<
ParentClass extends GenericTree<?, ?>,
ChildClass extends GenericTree<?, ?>>
{
// Attributes
private ArrayList<ChildClass> children = new ArrayList<ChildClass>();
private ParentClass parent = null;
// Methods
public void setParent(ParentClass parent) {
this.parent = parent;
}
public void addChild(ChildClass child) {
child.setParent(this);
this.children.add(child);
}
}
問題は、命令:child.setParent(this)にあります。
Javaは次のエラーを出します:
バインドの不一致:タイプChildClassのメソッドsetParent(?)は、
引数(GenericTree)には適用できません。ワイルドカードパラメータ?下限はなく、実際には引数GenericTreeよりも制限が厳しい可能性があります
私が欲しいのは、次のようなものを表現できるようにすることです。
public class GenericTree<
ParentClass extends GenericTree<?, ?>,
ChildClass extends GenericTree<[THIS_VERY_CLASS], ?>>
子クラスの親クラスはそれ自体である必要があると言うには...
自己境界ジェネリックに関するいくつかの記事を見てきましたが、この場合の適用方法がわかりません。
どんな助けでもいただければ幸いです。