gpt4 book ai didi

java - 泛型编译错误: type argument is not within bounds of type-variable S

转载 作者:行者123 更新时间:2023-12-02 03:06:22 25 4
gpt4 key购买 nike

这是我正在研究的对象模型的简化版本。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com