java - 如何在继承中使用泛型?

标签 java generics

我写了一些带有继承的泛型,但无法使其工作类型安全。我的目标是提供一个通用的 BaseService,无论 base 对象是 Foo extends BaseBar 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();
}

最佳答案

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

My goal is to provide a general BaseService on that I can exection the action(base) method, no matter if the base object is a Foo extends Base or Bar extends Base.

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

作为getService()的返回类型是BaseService<? extends Base> , 编译器甚至不知道 T 是什么是(除了它是 Base 的一些未知子类型)所以你不能调用 action方法。但是即使getService()的返回类型将是 FooService , 参数类型 T将是 Foo , 所以你不能用 Base 类型调用它.

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

关于java - 如何在继承中使用泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15736601/

相关文章:

在 Chrome 中通过 Selenium webDriver 运行测试用例时出现 java.lang.NullPointerException

.net - 从 VB.NET 中的 List(Of T) 中删除重复项

Java 递归泛型和通配符

generics - 完整、高效的 NumericLiteral 模块实现

java - Neo4j 非托管扩展中的类路径

java - SWIG:使用 %typemap(javabase) 并在 Java 中调用父类(super class)构造函数

java - 单击Java服务器页面/Java动态创建一个带有 “button”的文件夹

java - Storm Ui 错误 kafka spout,未使用 HDP

Java 泛型 : Is there difference between List<E> and List<? >?

c# - 从表达式函数获取属性