如何使 <T extends E> 泛型类型参数包含在内?

Tom*_*ica 5 java generics inheritance

我有一个界面:

  /**
   * 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);
  }
Run Code Online (Sandbox Code Playgroud)

在一种情况下,我想使用接口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;
  }
Run Code Online (Sandbox Code Playgroud)

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>)
Run Code Online (Sandbox Code Playgroud)

我的问题作为图像:

图片说明

use*_*306 2

public <T extends GameObject, V> List<V> enumValues(List<T> list, ValueGetter<T, V> reader) {
    List<V> vals = new ArrayList();

    for(T o : list) {
        vals.add(reader.getValue(o));
    }
    return vals;
}
Run Code Online (Sandbox Code Playgroud)