这是我正在研究的对象模型的简化版本。
public class GenericsTest {
public interface FooInterface {
public void foo();
}
public class Bar implements FooInterface {
public void foo() {}
}
public interface GenericInterface <T> {
public T func1();
}
public class Service implements GenericInterface<Bar> {
@Override
public Bar func1() {
return null;
}
}
public class GenericBar <S extends GenericInterface<FooInterface>> {
public S s;
public GenericBar() {}
}
public static void main(String[] args) {
GenericBar<Service> serviceGenericBar; // <-- compilation error at this line
<... more code ...>
}
}
编译器错误:type argument GenericsTest.Service is not within bounds of type-variable S
IDE (intellij) 显示有关错误的更多详细信息:Type parameter 'GenericsTest.Service' is not within its bound; should implement GenericsTest.GenericInterface<GenericTests.FooInterface>
Service
类正在实现 GenericInterface。我查看了其他几个具有相同错误的问题,但它们没有为这个特定场景提供线索。关于如何解决这个问题有什么想法吗?
最佳答案
问题正是两个编译器告诉你的:输入 Service
不在输入 GenericBar
的范围内需要其类型参数 S
。具体来说,GenericBar
需要 S
其实现的参数绑定(bind)到扩展 GenericInterface<FooInterface>
的类型。 Service
不满足该要求。
Service
实现GenericInterface<Bar>
,这两者都不是 GenericInterface<FooInterface>
也不是该类型的扩展,事实上 Bar
实现FooInterface
虽然。您不能分配 List<String>
到 List<Object>
类型的变量,出于基本相同的原因。
可以通过修改类GenericBar
的定义来解决编译错误像这样:
public class GenericBar <S extends GenericInterface<? extends FooInterface>> {
public S s;
public GenericBar() {}
}
这是否是您真正想要使用的是一个完全不同的问题,只有您可以回答。
关于java - 泛型编译错误: type argument is not within bounds of type-variable S,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41685066/