如果一个数据类,其中一个字段类型可能为多种,那么这个数据类就可以写为泛型类。最常见的就是服务端返回的响应数据Response。这个数据类里面status字段与msg字端类型固定,只有data这个字段存在多种类型数据的可能,因此就用通配符T来替代这个字段类型。比如:
public class TzCloudResponse{ protected int status; protected T data; protected String msg; public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public T getData() { return data; } public void setData(T data) { this.data = data; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public boolean isResponseSuccess(){ return status == 1; } }
显然,拿到服务端的响应Response后,需要对其body进行json解析,这时候就需要知道TzResponse
这个解析的接口为:
public abstract class TzBaseCloudCallbackextends Callback > { @Override public TzCloudResponse parseNetworkResponse(Response response, int i){ try { String responseStr = response.body().string(); TzCloudResponse result = new Gson().fromJson(responseStr,getType()); return result; }catch (Exception e){ Lg.printException(e); } return null; } @Override public void onError(Call call, Exception e, int i) { Lg.printException(e); doOnError(call, e, i); } protected abstract void doOnError(Call call, Exception e, int i); protected abstract Type getType(); }
然后针对每个功能接口实现不同的getType,比如我上传文件的回调就可以写成:
mUploadRequestCall.execute(new TzBaseCloudCallback(){ @Override protected void doOnError(Call call, Exception e, int i) { callBack.onError(); } @Override protected Type getType() { return new TypeToken >(){}.getType(); } @Override public void onResponse(TzCloudResponse response, int i) { if(response != null && response.isResponseSuccess()){ callBack.onSuccess(response.getData()); }else{ callBack.onError(); } } });
这样json 解析就没有问题了。
这样可以避免构建多个数据类,也避免了构建多个回调接口,这就是传说中的多态吧,整挺好。



