OK回调接口数据类型-泛型回调

在OK请求完成之后:

handler.post(new Runnable() {
    @Override
    public void run() {
        Class genericUtil = GenericUtil.getGenericUtil(okCallback.getClass());//运用GenericUtil类返回泛型数据
        Object o = GsonUtil.getGsonInstence().fromGson(string, genericUtil);//Gson解析

        okCallback.onSuccess(o);   //返回数据
    }
}); 
  
接口:
public interface OKCallback<T> {
    void onSuccess(T t);
    void onFalsed(Exception e);
}
接收数据,实现的接口:
public abstract class OKEntityCallback<T> implements OKCallback<T>{

    protected Class<T> cla;

    public OKEntityCallback() {
        this.cla = GenericUtil.getGenericUtil(this.getClass());
    }
}
数据回调,泛型转换:
public class GenericUtil {
    public static <T> Class<T> getGenericUtil(Class cla){
        Type genericSuperclass = cla.getGenericSuperclass();
        Class<T> result = null;
        if(genericSuperclass instanceof ParameterizedType){
            ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
            Type[] types = parameterizedType.getActualTypeArguments();
            result = (Class<T>) types[0];
        }
        return result;
    }
}
 
  
最终回调数据:
OKHttpUtil.getInstence().get(path, new OKEntityCallback() {   //泛型先加上,再重写回家接口的方法
    @Override
    public void onSuccess(OKTestBean okTestBean) {
        Log.e("Test",okTestBean.toString());
    }

    @Override
    public void onFalsed(Exception e) {
        Log.e("Test","NO");
    }
});


你可能感兴趣的:(OK回调接口数据类型-泛型回调)