简体   繁体   中英

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:

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 .

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. 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.

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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