Gson处理解析泛型类型对象,直接在泛型当前类获取泛型的类型
public abstract class CallBack<T> {
//获取解析传递过来的泛型类型(在泛型当前类中获取)
public Type getType() { ParameterizedType genType = (ParameterizedType) getClass().getGenericSuperclass(); Type[] actualTypeArguments = ((ParameterizedType) genType).getActualTypeArguments(); return actualTypeArguments[0]; }
public abstract void onSuccess(T result); @Override public void onSuccess(String responseInfo,int stateCode) { Gson gson = new Gson(); try { if (stateCode == 200) { Type type = getType(); if (type == String.class) { onSuccess((T) responseInfo); } else if (type == List.class) {
//list没有指定泛型类型的
onSuccess((T) gson.fromJson(responseInfo, type));
} else if (type == Map.class) {
//map没有指定泛型类型的
onSuccess((T) gson.fromJson(responseInfo, type));
} else if (type instanceof ParameterizedType && ((ParameterizedType) type).getActualTypeArguments().length == 1) {
//List指定泛型类型的
onSuccess((T) gson.fromJson(responseInfo, type));
} else if (type instanceof ParameterizedType && ((ParameterizedType) type).getActualTypeArguments().length == 2) { //map指定泛型类型的
onSuccess((T) gson.fromJson(result, type));
} else {
//其它单个对象类型 onSuccess((T) gson.fromJson(responseInfo, type)); } } else { onFailure(new HttpException()); } } catch (JsonSyntaxException e) { e.printStackTrace(); onFailure(new HttpException(e.getMessage())); } }
}