Document
オブジェクト内にFolder
オブジェクトを保持するジェネリック クラスのセットを設計しています。
// Folder, which holds zero or more documents
public interface Folder<DocType extends Document>
{
// Locate matching documents within the folder
public ArrayList<DocType> findDocuments(...);
...
}
// Document, contained within a folder
public interface Document
{
// Retrieve the parent folder
public Folder getFolder(); // Not correct
...
}
これらのクラスは、フォルダおよびドキュメント タイプの実際の実装のために拡張されます。問題は、Document.getFolder()
メソッドがタイプ のオブジェクトを返す必要があることです。Folder<DocType>
ここで、DocType
は の実際の実装タイプですDocument
。つまり、メソッドはそれ自身の具象クラス タイプが何であるかを知る必要があります。
だから私の質問は、Document
クラスが代わりに次のように宣言されるべきかということです:
// Document, contained within a Folder
public interface Document<DocType extends Document>
{
// Retrieve the parent folder
public Folder<DocType> getFolder();
...
}
または、これを行う簡単な方法はありますか?上記のコードでは、具体的な実装が次のようになっている必要があります。
public class MyFolder
implements Folder<MyDocument>
{ ... }
public class MyDocument
implements Document<MyDocument>
{ ... }
私Document<MyDocument>
には少し奇妙に思える部分です。本当に必要ですか?
(これが重複している場合は申し訳ありません。アーカイブで探していた正確な答えを見つけることができませんでした。)
補遺
上記の元のコードでは が使用されArrayList<DocType>
ていましたが、いくつかのポスターが指摘しているようにList
、たとえば次のように を返す方がよいでしょう。
public List<DocType> findDocuments(...);
(そのメソッドは私の問題にとって重要ではなく、実際の API は を返すIterator
ため、質問を単純化するために頭に浮かんだ最初のものを使用しました。)