获取类:
public static <T>T getT(Object o,int i){
ParameterizedType parameterizedType = (ParameterizedType) o.getClass().getGenericSuperclass();
Type type = parameterizedType.getActualTypeArguments()[i];
Class<T> t = (Class<T>) type;
try {
T t1 = t.newInstance();
return t1;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
获取接口:
try {
String data = responseBody.string();
Type[] types = netCallBack.getClass().getGenericInterfaces();
Type[] ty = ((ParameterizedType) types[0]).getActualTypeArguments();
Type t = ty[0];
Gson gson = new Gson();
T gson_FT = null;
gson_FT = gson.fromJson(data, t);
netCallBack.onSuccess(gson_FT);
} catch (IOException e) {
e.printStackTrace();
}
本文介绍了如何使用Java泛型来获取类和接口的具体类型参数。通过示例代码展示了如何从对象中提取泛型类型,并利用Gson进行JSON解析。这对于需要处理泛型类或实现泛型接口的场景非常有用。
1455

被折叠的 条评论
为什么被折叠?



