2

我写了一些带有继承的泛型,但不能让它工作类型安全。我的目标是提供一个BaseService关于我可以执行该action(base)方法的一般信息,无论base对象是 aFoo extends Base还是Bar extends Base.

以下不起作用,为什么?

class Base;
class Foo extends Base;

interface BaseService<T extends Base> {
    void action(T base);
}

class FooService implements BaseService<Foo> {
    void action(Foo foo) {
    }
}


//usage:
//complains that the method is not applicable for the argument,
//and that I should change action(T) to action(Base). Why?
Base base;
getService().action(base);


//just to demonstrate the problem
BaseService<? extends Base> getService() {
    return new FooService();
}
4

1 回答 1

1

泛型的存在是为了进行静态类型检查。当你写

我的目标是提供一个通用的 BaseService,无论基础对象是 Foo extends Base 还是 Bar extends Base,我都可以执行 action(base) 方法。

您表明您不需要任何静态类型检查。所以要做到这一点,参数类型应该是Base而不是T.

由于getService()is的返回类型BaseService<? extends Base>,编译器甚至不知道是什么T(除了它是 的某些未知子类型Base),因此您根本无法调用该action方法。但是即使返回类型getService()FooService,参数类型T也是Foo,所以你不能用 type 来调用它Base

您可能应该多考虑一下您实际上希望编译器通过使用泛型来检查什么。

于 2013-04-02T12:45:39.797 回答