java如何用<S extends T>Iterable<S>
我试图创建Spring类Crudepository的模拟实现,但找不到如何实现此方法:
public <S extends T> Iterable<S> save(Iterable<S> iterable)
例如,我有:
private class CrudRepositoryMock implements CrudRepository<String, String> {
// works fine, the method is correctly overridden
// method signature in interface : public <S extends T> S save(S s)
@Override
public String save(String s) {
return null;
}
// does not work, IntelliJ tells me that the method does not override
// from the superclass
// method signature in interface :
// <S extends T> Iterable<S> save(Iterable<S> iterable)
@Override
public Iterable<String> save(Iterable<String> iterable) {
return null;
}
}
其他方法已成功重写。我只是不知道应该写些什么来正确地用Iterable重写这个方法
有什么想法吗
多谢各位
# 1 楼答案
使用EclipseIDE的“覆盖/实现方法”快捷方式,我得到
然而,这会产生一个警告;也就是说,
String
是最终的,不能扩展。您可以传入String
对象,但是按照约定final
类不应该由泛型使用# 2 楼答案
这是因为由于参数是
S extends T
,所以Iterable
需要一个S extends String
,而String
是不够的考虑如下:如果^ {< CD5>},您应该允许调用^ {< CD6>},并返回^ {< CD7>},这与^ {CD8>}不兼容。
您需要保留泛型
S
:# 3 楼答案
请注意,S是由该方法声明的类型参数,因此
Iterable<S extends String>
不是Iterable<String>
,允许字符串的子类型(这不是一个很好的示例),而后者不允许依附于接口的正确覆盖将是