gpt4 book ai didi

android - 改造,通用调用类型

转载 作者:太空宇宙 更新时间:2023-11-03 11:04:28 29 4
gpt4 key购买 nike

很抱歉,如果我的标题含糊不清,但我找不到更好的。

我有一个以这种方式公开服务的休息 Api:/api/{type}/{id} 4 个“类型”,因此返回 4 个类类型。

所有这些类都继承自同一个父类(super 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;
}

这感觉很不对。

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

谢谢,

最佳答案

我最后做的是为我的 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,因为它可以轻松更改。

关于android - 改造,通用调用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35439525/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com