簡體   English   中英

通用返回方法,由方法中的通用參數定義

[英]Generic return Method to be defined by generic parameter in method

我在Java中有一個接口:

public interface IElement{

    public String getId();
    public String getName();

    /***
     * adds an IElement to this elements children
     * @param child
     */
    void getAddChild(IElement child);

    /***
     * returns all children
     * @return
     */
    Collection<IElement> getChildren( );

    /***
     * returns all children which match the Class of the passed IElement
     * @param eType - the class type to match
     */ 
    Collection<IElement> getChildren( Class<? extends IElement> eType);
}

這個想法是一個IElement可以包含其他IElement的集合。

我需要方法Collection<IElement> getChildren(Class<? extends IElement> eType)返回匹配兄弟姐妹的集合。

說我有三個類,所有類都擴展了IElement 一個叫做Room ,另一個叫做Boxbox1box2box3 ),另一個叫做Shelveshelve1

現在,有了一個Room實例,我可以執行以下操作:

room1.addChildren(box1);
room1.addChildren(box2);
room1.addChildren(shelve1,sheleve2);
room1.addChildren(box3);

現在我有一個Roomroom1 ,在它和三個箱) Shelveshelve1 )。 現在,我想使用Collection<IElement> getChildren(Class<? extends IElement> eType);獲取room1內的所有Box對象Collection<IElement> getChildren(Class<? extends IElement> eType); 方法,如在room1.getChildren(Box.class) 但是,該方法僅返回IElement的集合。 我希望它返回Collection<Box> 如果我通過了Shelve那么它應該返回Shelve對象的集合。

這可能嗎? 如果是這樣,您該怎么做? 我知道這似乎很奇怪,但是我有很多可以容納其他Elements的不同對象,並且我需要一種快速簡便的方法來過濾不同類型的對象。

您可以使用命名的泛型類型聲明泛型方法,而不使用通配符。

<E extends IElement> Collection<E> getChildren(Class<E> eType);

這樣,您獲取的集合的通用類型將與您傳入的類匹配。

您的實現將必須構造並為其參數返回適當的泛型類型的集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM