【问题标题】:Retrofit, Generic Call type改造,通用调用类型
【发布时间】:2016-02-17 19:58:42
【问题描述】:

对不起,如果我的标题如此含糊,但我找不到更好的。

我有一个以这种方式公开服务的 rest Api:/api/{type}/{id} 4 'type' 因此返回了 4 个 Class 类型。

所有这些类都扩展自同一个超类

我的问题是我似乎总是必须明确命名返回的类:

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

等等……

所以我现在做

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;
}

感觉很不对。

你有没有办法做得更好,也许是泛型?

谢谢,

【问题讨论】:

    标签: android retrofit retrofit2


    【解决方案1】:

    我最后做的是为我的 Api 类中的所有子类创建一个包装器:

    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;
    }
    

    并以这种方式使用它:

    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) {
                         ..........
                    }
                });
    

    我有一些未经检查的警告想法,但我仍然有开关。

    我考虑过的另一个解决方案是使用自定义 TypeConverter,它将(来自 json 响应)创建 TYPE1/TYPE2 元素并将其发送回 SuperClass 对象。但我不想测试 json,因为它可以轻松更改。

    【讨论】:

      猜你喜欢
      • 2018-04-06
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      相关资源
      最近更新 更多