AndroidUtil - 異步回調中的泛型傳遞 - 通過父類type方式,規避泛型擦除

import android.util.Log;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
// 如需強制調用者實現數據回調的方法,可做成abstract
 public class ModuleApiCallback<T> implements ApiCallback<T> {
     protected Type type;

     public SearchApiCallback() {
     this.type = ClassTypeReflect.getModelClazz(getClass());
     }

     @Override
     public void onErrorResponse(VolleyError volleyError) {

     }

     @Override
     public void onResponse(T t) {

     }
 }
 */

class ClassTypeReflect {
    static Type getModelClazz(Class<?> subclass) {
        return getGenericType(0, subclass);
    }

    private static Type getGenericType(int index, Class<?> subclass) {
        Type superclass = subclass.getGenericSuperclass();
        if (!(superclass instanceof ParameterizedType)) {
            return Object.class;
        }
        Type[] params = ((ParameterizedType) superclass).getActualTypeArguments();
        if (index >= params.length || index < 0) {
            throw new RuntimeException("Index outof bounds");
        }

        if (!(params[index] instanceof Class)) {
            return Object.class;
        }
        return params[index];
    }

}

發佈了28 篇原創文章 · 獲贊 46 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章