如何在具有泛型参数类型的接口中实现函数?

How to implement function in interface with generic argument types?

public interface Page<T> {
  T nextPage();
}

它的实现

public class ConcretePageA implements Page<TypeA> {
  public TypeA nextPage() {
    // do stuff
  }
}

然后我有一个接口消耗Page

public interface Source {
  <T> int getData(Page<T> page)
}

及其实现

public class ConcreteSourceA implements Source {
  public int getData(Page<TypeA> page) {   //error: getData in ConcreteSourceA clashes with getData in Source
    // do stuff
  }
}

我试过了,但也不行

public class ConcreteSourceA implements Source {
  public <TypeA> getData(Page<TypeA> page) { // error: expect com.foo.TypeA but got TypeA
    // do stuff
  }
}

当我执行上述操作时,出现编译错误

getData in ConcreteSourceA clashes with getData in Source

我知道我做错了什么,但是如何在仍然有多个使用不同类型的实现的情况下修复它?

我是不是一开始就做错了?泛型不是解决这个问题的正确方法吗?

看起来你想让 SourcePage 一样通用 - 就像这样:

public interface Source<T> {
  int getData(Page<T> page);
}

然后您可以定义仅实现特定特定化的实现,例如

public class ConcreteSourceA implements Source<TypeA> {
  public int getData(Page<TypeA> page) {
    // do stuff
    return 0;
  }
}