我有一個接口:如何使<T extends E>泛型類型參數包含在內?
/**
* Getter for any values within the GameObject and it's subclasses.
* Used as callback.
*
* Typical implementation would look like:
* new ValueGetter<SummonerSpell, String> {
* public String getValue(SummonerSpell source) {
* return source.toString();
* }
* }
* @param <T>
* @param <V> Type of value retrieved
*/
public static interface ValueGetter<T extends GameObject, V> {
public V getValue(T source);
}
在一種情況下,我想使用的接口GameObject
本身,而不是某些子類。我想這樣做在遊戲中的對象的List
:
/**
* Will call the given value getter for all elements of this collection and return array of values.
* @param <T>
* @param <V>
* @param reader
* @return
*/
public <T extends GameObject, V> List<V> enumValues(ValueGetter<T, V> reader) {
List<V> vals = new ArrayList();
for(GameObject o : this) {
vals.add(reader.getValue(o));
}
return vals;
}
但reader.getValue(o)
導致編譯器錯誤:
incompatible types: GameObject cannot be converted to T
where T,V are type-variables:
T extends GameObject declared in method <T,V>enumValues(ValueGetter<T,V>)
V extends Object declared in method <T,V>enumValues(ValueGetter<T,V>)
我的形象問題: