2015-10-21 59 views
3

我試圖弄清楚爲什麼編譯器會引發通用捕捉

test(capture<? extends Serializable>) in Predicate cannot be applied to (Serializable)

test(e.getValue().getData())和我怎麼能解決這個問題。

代碼拋出編譯器錯誤是以下

private Map<Predicate<? extends Serializable>, TaggedData<? extends Serializable>> scheduledData = new HashMap<>(); 

public synchronized <T extends Serializable> void conditionalSend(String tag, T data, Predicate<T> condition) { 
    scheduledData.put(condition, new TaggedData<T>(tag, data)); 
    scheduledData.entrySet() 
       .stream() 
       .filter(e -> e.getKey().test(e.getValue().getData())) 
       .forEach(e -> send(e.getValue())); 
} 

我TaggedData類是這樣定義的

class TaggedData<T extends Serializable> implements Serializable { 
    private static final long serialVersionUID = 1469827769491692358L; 

    private final String tag; 
    private final T data; 

    TaggedData(String tag, T data) { 
     this.tag = tag; 
     this.data = data; 
    } 

    String getTag() { 
     return tag; 
    } 

    T getData() { 
     return data; 
    } 
} 
+0

我在泛型通常不更動'',但不是禁止有一個''在賦值的右側通用??? '<>'運算符隱含的是哪一個? – Powerlord

+0

更改後,我無法在我的謂詞中使用我的數據,因爲它預計'?超級可序列化「。當我自己保持地圖中的類型同步時,我現在切換到Predicate和TaggedData的包裝對象列表。 – succcubbus

回答

1

想象一下,你通過Integer(這是Serializable)到Predicate<String>(其中extends Serializable )?這是毫無意義的。

Predicate#test()作爲消費者,因此您需要使用Predicate<? super Serializable>來代替。

瞭解更多:What is PECS (Producer Extends Consumer Super)?

+0

我去了 T data,Predicate succcubbus