java 泛型参数的类型_Java获得泛型参数类型
在Android開發(fā)中,使用Gson將json字符串轉(zhuǎn)換為Java對象尤為常見。在這個轉(zhuǎn)換過程中,通常會結(jié)合泛型參數(shù)、接口或者抽象類來封裝處理。
T t = new Gson().fromJson(response, type);
那如何來獲取type呢?
接口實現(xiàn)
public interface ICallback {
void onSuccess(T t);
void onFailure(String msg);
}
對于一個ICallback類型的callback而言:
// 返回實現(xiàn)的接口
Type[] genericInterfaces = callback.getClass().getGenericInterfaces();
if (genericInterfaces[0] instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) (genericInterfaces[0]);
// 僅包含一個泛型參數(shù)
Type type = parameterizedType.getActualTypeArguments()[0];
// T為String
if (type instanceof Class && TextUtils.equals(((Class>) type).getName(), String.class.getName())) {
callback.onSuccess((T) response);
return;
}
try {
T t = new Gson().fromJson(response, type);
callback.onSuccess(t);
} catch (Exception e) {
callback.onFailure("解析失敗");
}
}else {
// 無泛型參數(shù)
callback.onSuccess((T) response);
}
抽象類實現(xiàn)
public abstract class AbstractCallback {
protected abstract void onSuccess(T t);
protected abstract void onFailure(String msg);
}
同樣,對于一個AbstractCallback類型的callback而言:
Type superclass = callback.getClass().getGenericSuperclass();
if (superclass instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) superclass;
// 僅包含一個泛型參數(shù)
Type type = parameterizedType.getActualTypeArguments()[0];
// T為String
if (type instanceof Class && TextUtils.equals(((Class>) type).getName(), String.class.getName())) {
callback.onSuccess((T) response);
return;
}
try {
T t = new Gson().fromJson(response, type);
callback.onSuccess(t);
} catch (Exception e) {
callback.onFailure("解析失敗");
}
} else {
// 無泛型參數(shù)
callback.onSuccess((T) response);
}
總結(jié)
以上是生活随笔為你收集整理的java 泛型参数的类型_Java获得泛型参数类型的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 单例 生命周期_单例模式---
- 下一篇: 查看文件Linux命令(查看linux文