80,350
社区成员
发帖
与我相关
我的任务
分享
public class HttpResponse<T> implements Serializable {
private int code;
private String msg;
private boolean success;
private T result;
// get set.....
}
static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
}
java.lang.ClassCastException: com.google.gson.internal.StringMap cannot be cast to com.xxx.xxx.bean.LoginInfo
public class MainHttpResponse implements Serializable {
private int code;
private String msg;
private boolean success;
// get set.....
}
定义具体的子类就是
public class LoginInfoResponse extends MainHttpResponse {
private LoginInfo result;
// get set……
}
至于ResultCallback的定义的格式是
public abstract class ResultCallback<T extends MainHttpResponse >{
private Class<T> entityClass = null;
/**
* 获取泛型T的Class
* @return
*/
public Class<T> getEntityClass() {
Type t = getClass().getGenericSuperclass();
if(t instanceof ParameterizedType){
Type[] p = ((ParameterizedType)t).getActualTypeArguments();
entityClass = (Class<T>)p[0];
}
return entityClass;
}
// other method
}
在请求返回结果解析时就用这个getEntityClass来获取类型解析,
T result = new Gson().fromJson(resultStr, resultCallBack.getEntityClass());
返回的T就是LoginInfoResponse等子类,可以直接使用。
需要对每种请求结果都要建立一个结果类型。