繁体   English   中英

泛型编译错误:类型参数不在类型变量S的范围内

[英]generics compilation error: type argument is not within bounds of type-variable S

这是我正在处理的对象模型的简化版本。

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> Type parameter 'GenericsTest.Service' is not within its bound; should implement GenericsTest.GenericInterface<GenericTests.FooInterface>

Service类正在实现GenericInterface。 我看过其他几个具有相同错误的SO问题,但它们没有为这种特定情况提供线索。 有想法该怎么解决这个吗?

问题恰恰是两个编译器告诉您的: Service类型不在GenericBar类型对其类型参数S要求的范围之内。 具体来说, GenericBar要求将其实现的S参数绑定到扩展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() {}
}

这是否是您实际使用的是完全不同的问题,只有您可以回答。

当您更改Service来实现GenericInterface时,代码将进行编译。

public class Service implements GenericInterface<FooInterface> {
    @Override
    public Bar func1() {
        return null;
    }
}

或者,如果您希望将服务限制为仅基于Bar,则可以更改GenericBar,这样它将变得更加通用:

public class Service implements GenericInterface<Bar> {
    @Override
    public Bar func1() {
        return null;
    }
}

public class GenericBar<S extends GenericInterface<? extends FooInterface>> {
    public S s;

    public GenericBar() {
    }
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM