简体   繁体   中英

Retrofit, Generic Call type

I'm sorry if my title is so vague but I couldn't find better.

I have a rest Api that expose a service this way : /api/{type}/{id} 4 'type' and therefore 4 Class types that are returned.

All this Classes extends from the same SuperClass

My problem is that I seem to always have to explicitly name the returned class :

Call<Type1> call = apiInterface.get....
Call<Type2> call = apiInterface.get....

etc...

so for now I do

SuperClass object = null;
switch(type){
    case TYPE1:
       Call<Type1> call = apiInterface.getType1(id);
       call.enqueue(new Callback....{
            .......
            object = response.body()
       }
       break;
    case TYPE2:
       Call<Type2> call = apiInterface.getType2(id);
       call.enqueue(new Callback....{
            .......
            object = response.body()
       }
       break;
}

which feels quite wrong.

Would you have a way to do it better, maybe something with generics ?

Thanks,

What I finaly did is create a wrapper for all my subclasses in my Api Class :

public Call getCourseElement(Type type, String id){
    Call call = null;
    switch (type) {
        case TYPE1:
            call = apiInterface.getType1(id);
            break;
        case TYPE2:
            call = apiInterface.getType2(id);
            break;
        ...
    }
    return call;
}

And use it this way :

Call call = api.getCourseElement(type, id);
            call.enqueue(new Callback() {
                @Override
                public void onResponse(Response response, Retrofit retrofit) {
                     SuperClass superObj = (SuperClass) response.body()
                     ...........
                }

                @Override
                public void onFailure(Throwable t) {
                     ..........
                }
            });

I have some unchecked warning thought, and I still have the switch.

One other solution that I have thought about is to use a custom TypeConverter that would (from the json response) create a TYPE1/TYPE2 element and send it back in a SuperClass object. But I don't want to test the json as it can easely change.

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