Gson-TypeToken获取泛型参数的类型
2019-09-27 本文已影响0人
MonkeyLei
早期我们封装通用网络请求(基于rx)的时候已经包装了下,其实就是参考了Gson的TypeToken的写法:
/**
* Returns the type from super class's type parameter in {@link $Gson$Types#canonicalize
* canonical form}.
*/
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]);
}
我们的 ResultCallBack.java - 做成了抽象类鸭,做成实体类也可以,但是也必须这样写(new ResultCallBack<List<XXX>>(){}.mType;), 后面看TypeToken用法就知道了...
/*
*@Description: 获取泛型实体类类型
*@Author: hl
*@Time: 2019/1/18 14:10
*/
public abstract class ResultCallBack<T> {
public Type mType;
public ResultCallBack() {
mType = getSuperclassTypeParameter(getClass());
}
public 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]);
}
public Class getClassType(){
return getClass();
}
}
然后看TypeToken用法实 践:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
public class TestFanXing {
public class BBQ{
private int id;
private String name;
}
public static void main(String[] args){
String jsonData = "{\"id\": 1, \"name\": \"黄磊\"}";
String jsonArray = "[{\"id\": 1, \"name\": \"黄磊\"},{\"id\": 2, \"name\": \"黄磊2号\"},{\"id\": 3, \"name\": \"黄磊3号\"}]";
Gson gson = new Gson();
BBQ bbq = gson.fromJson(jsonData, BBQ.class/*new TypeToken<BBQ>(){}.getType()*/);
System.out.println("id=" + bbq.id);
System.out.println("name=" + bbq.name);
Type type = new TypeToken<List<BBQ>>(){}.getType();
List<BBQ> bbqs = gson.fromJson(jsonArray, type);
System.out.println("id2号=" + bbqs.get(0).id);
System.out.println("name2号=" + bbqs.get(0).name);
}
}
image
有时候需要借助泛型做通用性封装的时候,可以考虑下。。减少重复代码很多时候还是蛮有用的鸭!.....之前也补过这方面知识,不过这里还想再关联强调加强下记忆!。。。