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

标签 java generics

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

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/

相关文章:

java - BouncyCaSTLe 类上的 NoClassDefFoundError

java - Android 应用程序与 PLC 通信

c# - .net中Contiguous memory存储的误区?

c# - 如何比较T与T?

java - 收集参数以应用于 Java/Scala 中的柯里化(Currying)函数

java - 泛型方法中类类型参数的使用

java - 是否可以将 Java ME API 或 Android API 用于 800x600 触摸屏显示器?

java - 具有可拖动日期范围的日期选择器/日历 UI 组件

java - Android:使用 SSL 交换消息时出现问题

java - 具有两种或多种类型(接口(interface))错误的类的泛型