[英]How to instantiate a collection containing a complex generic type
I'm using a third-party type defined like this:我正在使用这样定义的第三方类型:
abstract public class BaseRequest<T extends BaseRequest<T, R>, R extends BaseResponse>
I want to maintain a Queue of objects of this type and execute the requests periodically.我想维护一个此类对象的队列并定期执行请求。 I have the syntax down for the
execute
method:我有
execute
方法的语法:
protected <T extends BaseRequest<T, R>, R extends BaseResponse> void execute(T request, int tryCount) {
What I can't figure out how to do is instantiate a Queue that contains objects of this type.我不知道该怎么做是实例化一个包含这种类型对象的队列。 I'm not even sure if this is possible and would also settle for a
Queue<BaseRequest<?, ?>>
but then can't figure out how to cast to the type I need when I invoke execute
.我什至不确定这是否可能并且也会满足于
Queue<BaseRequest<?, ?>>
但是当我调用execute
时无法弄清楚如何转换为我需要的类型。
I'm sure this has been answered before so apologies for that but I don't know how to phrase the question in a way where I can search for the answer.我确信这个问题之前已经得到了回答,对此我深表歉意,但我不知道如何以一种我可以搜索答案的方式来表达这个问题。
Edit, here's a stripped-back version of the execute
method showing why I require typed objects.编辑,这是
execute
方法的精简版本,显示了为什么我需要类型化对象。 The thirdPartyApiWrapper
has an execute signature that includes a callback interface that I must implement with an anonymous inner class, which requires the types to be specified. thirdPartyApiWrapper
有一个执行签名,其中包括一个回调接口,我必须使用匿名内部 class 实现该接口,这需要指定类型。
protected <T extends BaseRequest<T, R>, R extends BaseResponse> void execute(T request) {
thirdPartyApiWrapper.execute(request, new Callback<T, R>() {
@Override
public void onResponse(BaseRequest request, BaseResponse response) {
}
@Override
public void onFailure(BaseRequest request, IOException e) {
}
});
}
By putting things into a Queue<BaseRequest<?, ?>>
, you are losing the type information about the BaseRequest
, as you know.如您所知,通过将内容放入
Queue<BaseRequest<?, ?>>
,您将丢失有关BaseRequest
的类型信息。
You can't recover this at the time you want to execute it, which you would need in order to pass in the callback.您无法在要执行它时恢复它,您需要它才能传递回调。
I would suggest that you instead maintain a queue of instances which hold the BaseRequest
and a compatible callback together:我建议您改为维护一个实例队列,这些实例将
BaseRequest
和兼容的回调放在一起:
class RequestAndCallback<T, R> {
RequestAndCallback(BaseRequest<T, R> request, Callback<T, R> callback) {
// store in fields.
}
void execute() {
thirdPartyApiWrapper.execute(request, callback);
}
}
Note that you don't need to know the type parameters in order to call execute()
here: you can just have a Queue<RequestAndCallback<?, ?>>
, and work your way through that.请注意,您无需知道类型参数即可在此处调用
execute()
:您可以只拥有一个Queue<RequestAndCallback<?, ?>>
,然后按照自己的方式进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.