繁体   English   中英

如何创建带有任何类型参数的通用方法?

[英]How to create generic methods that take any type parameter?

我有一个抽象的超级服务,应该执行一些常见的逻辑。 几个服务实现了这个超级服务。 我根据条件选择了ServiceImpl,并希望将其分配给抽象类型,以便以后运行通用逻辑。

以下是什么问题? 我想将BaseResponse或扩展BaseResponse任何对象传递给process()方法,例如我的示例中的FirstResponse

//superservice
abstract class AbstractService<T extends BaseResponse> {
    public void process(T t) {
        //execute logic that is common to a BaseResponse
    }
}

//implementations
class FirstService extends AbstractService<FirstResponse extends BaseResponse> {
}

//usage
AbstractService<? extends BaseResponse> myservice = new FirstService(); //chose by condition
myservice.process(new FirstResponse()); //ERROR

结果:

    The method build(capture#2-of ? extends BaseResponse) 
in the type AbstractService<capture#2-of ? extends BaseResponse> is not applicable for the arguments (FirstResponse)
    //execute logic that is common to a BaseResponse

如果是这种情况,继承提供的灵活性就足够了,您实际上并不需要泛型。

public void process(BaseResponse t) {
    // ...
}

错误的原因是,Java编译器仅知道myserviceAbstractService<? extends BaseResponse> AbstractService<? extends BaseResponse> 以后将myservice重新分配给另一个子类是没有错的:

AbstractService<? extends BaseResponse> myservice = new FirstService();
myservice = new SecondService(); // <---------- should be ok
myservice.process(new FirstResponse()); // <--- making this bad

可能是一个真正的错误。 如果需要保留process(T)的接口,则必须更改myservice的类型,然后:

FirstService myservice = new FirstService();
myservice.process(new FirstResponse());

您可以使用如下泛型来实现:

abstract class AbstractService<T extends BaseResponse> {
    public void process(T t) {
        //execute logic that is common to a BaseResponse
    }
}

//implementations
class FirstService extends AbstractService<FirstResponse> {
    @Override
    public void process(FirstResponse firstResponse) {
        super.process(firstResponse);
        ...
    }
}

public static void main(String[] args) {
    //usage
    AbstractService<FirstResponse> myservice = new FirstService(); 
    myservice.process(new FirstResponse()); 
}

暂无
暂无

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

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