我有一个抽象的超级服务应该执行一些通用的逻辑。多个服务实现这个超级服务。我根据条件选择了ServiceImpl,并希望将其分配给抽象类型,以便稍后运行公共逻辑。如何创建采用任何类型参数的泛型方法?
以下哪项有问题?我想通过process()
方法传入/扩展BaseResponse
的任何对象,如我的示例中的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)
是否'与FirstService'工作' BaseResponse',或者'BaseResponse'的任何子类,或者一个特定的子类? – Bohemian
我觉得'AbstractService <?超级BaseResponse> myservice = new FirstService()'应该做的伎俩不是这样吗? –
'FirstService'将与'BaseResponse'一起使用; '? super'会调用'myservice.process()',但是我不能再分配'FirstService' ... – membersound