Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将泛型与继承一起使用?_Java_Generics - Fatal编程技术网

Java 如何将泛型与继承一起使用?

Java 如何将泛型与继承一起使用?,java,generics,Java,Generics,我编写了一些带有继承的泛型,但无法使其在类型安全的情况下工作。我的目标是提供一个通用的BaseService,我可以在此基础上执行action(base)方法,无论base对象是Foo extends base还是Bar extends base 以下内容不起作用,为什么 class Base; class Foo extends Base; interface BaseService<T extends Base> { void action(T base); } cl

我编写了一些带有继承的泛型,但无法使其在类型安全的情况下工作。我的目标是提供一个通用的
BaseService
,我可以在此基础上执行
action(base)
方法,无论
base
对象是
Foo 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();
}
类基;
类Foo扩展了基;
接口基本服务{
空洞作用(T基);
}
类FooService实现BaseService{
无效操作(Foo-Foo){
}
}
//用法:
//抱怨该方法不适用于该论点,
//我应该把动作(T)改为动作(Base)。为什么?
基地;
getService()操作(基本);
//只是为了证明这个问题

BaseService泛型用于静态类型检查。当你写的时候

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

您表示不需要任何静态类型检查。为此,参数类型应该是
Base
,而不是
T


由于
getService()
的返回类型是“.”的
baseservices可能的副本。如果是这样,我该怎么做才能使我的示例正常工作?它已经是类型安全的了。太安全了。我认为你根本不需要泛型。不,这不是因为它不可编译…这不是泛型的好选择,因为你总是返回
FooService
-例如,能够将其视为
BaseService
会破坏类型安全性。