簡體   English   中英

列表中具有通用方法參數類型的接口

[英]Interface with generic method parameter type in list

我有一個將特定RequestType鏈接到單獨的LinkedList的HashMap。 列表由具有通用類型的接口組成。 將地圖添加到列表中沒有問題,但似乎無法從地圖中獲取列表。

我將向您展示我的兩次嘗試,以及相應的錯誤。 首先,當我想在接口中調用方法時,將向您展示該接口和我的Map。

public interface IRequestListener<Result> {
    public void resultUpdated(Result result);
}

private HashMap<RequestType, LinkedList<IRequestListener<?>>> requestListenerMap = 
    new HashMap<RequestType, LinkedList<IRequestListener<?>>>();

在下面的代碼中,RequestType和Notification是兩個簡單的枚舉。

這是第一次嘗試:

Notification notification = Notification.AVOID;
LinkedList<IRequestListener<?>> listeners = 
    requestListenerMap.get(RequestType.NOTIFICATION);
for(IRequestListener<?> listener : listeners) {
    listener.resultUpdated(notification); // ERROR ON THIS LINE
}

這將導致以下錯誤:

The method resultUpdated(capture#1-of ?) in the type 
IRequestListener<capture#1-of ?> is not applicable for 
the arguments (Notification)

這是第二次嘗試:

Notification notification = Notification.AVOID;
LinkedList<IRequestListener<Notification>> listeners = 
    requestListenerMap.get(RequestType.NOTIFICATION); // ERROR ON THIS LINE
for(IRequestListener<Notification> listener : listeners) {
    listener.resultUpdated(notification);
}

這將導致以下錯誤:

Type mismatch: cannot convert from LinkedList<IRequestListener<?>> 
to LinkedList<IRequestListener<Notification>>

我以為我被泛型棘手的繼承/轉換問題絆倒了,但我不知道怎么做。 我不想擴展Notification,因為此時界面中的Result可以是Notification或Integer。 以后我可能還會添加將List作為結果的可能性。

干杯。

聽起來您想限制Result類型參數以擴展Notification

private HashMap<RequestType, LinkedList<IRequestListener<? extends Notification>>> 
    requestListenerMap = new HashMap<>(); // Assuming Java 7

...

LinkedList<IRequestListener<? extends Notification>> listeners = 
    requestListenerMap.get(RequestType.NOTIFICATION);
for(IRequestListener<? extends Notification> listener : listeners) {
    listener.resultUpdated(notification);
}

現在,如果這不適用於地圖聲明-因為您想存儲其他條目的其他列表-您可能需要不安全的類型轉換:

private HashMap<RequestType, LinkedList<IRequestListener<?>>> requestListenerMap = 
    new HashMap<RequestType, LinkedList<IRequestListener<?>>>();

...

LinkedList<IRequestListener<?>> listeners = 
    requestListenerMap.get(RequestType.NOTIFICATION);
for (IRequestListener<?> listener : listeners) {
    // Note that this cast is unsafe.
    IRequestListener<? extends Notification> notificationListener = 
        (IRequestListener<? extends Notification>) listener;
    notificationListener.resultUpdated(notification);
}

從根本上講,您不能安全地執行此操作,因為執行時類型將不包含type參數。 但是,如果調用resultUpdated不適當,則會收到ClassCastException

暫無
暫無

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

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