今天在做解析网络请求后得到的数据的转化的时候用到了:getGenericInterfaces这个方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	
/**
* 获取回调接口中 T 的具体类型
*
* @param clazz
* @return
*/
public static Type getTType(Class clazz) {
//以Type的形式返回本类直接实现的接口.
Type[] types = clazz.getGenericInterfaces();
if (types.length > 0) {
//返回表示此类型实际类型参数的 Type 对象的数组
Type[] interfacesTypes = ((ParameterizedType) types[0]).getActualTypeArguments();
return interfacesTypes[0];
}
return null;
}

其中回调接口为:

1
2
3
4
5
6
7
8
9
10
11
new RequestListener <> () {
@Override
public void onSuccess (List result){
}
//在解析数据的时候这样操作,目的是为了对所有返回的数据进行数据转化为所指定的类型:

Type type = getTType(requestListener.getClass());
//泛型是实体或者List等类型
T t = JsonUtils.fromJson(resultString, type);
requestListener.onSuccess(t);
}

类RequestListener为:

1
2
3
4
public interface RequestListener {
void onSuccess(T result);
void onError(Exception e);
}

使用Gson进行json的解析,T fromJson(String json, Type typeOfT);那么怎么才能获取到RequestListener中的的类型呢?
于是我们从接口获取参数化类型处理。

官方文档解释

getGenericInterfaces:

Returns the {@code Type}s representing the interfaces directly implemented by the class or interface represented by this object.释意:返回表示由此对象表示的类或接口直接实现的接口的{@code Type}。

getInterfaces:

Determines the interfaces implemented by the class or interface represented by this object.
释意:返回由此对象表示的类或接口实现的接口。

从解释上面来看出来了,差异在于“接口实现的接口的Type”,接下来用具体示例来解释区别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private class Food{
String foodName;
}
private interface Eat{
void eat(String things);
}
private interface Run{
void run();
}
private class Dog implements Eat,Run{
@Override
public void run() { }
@Override
public void eat(String things) { }
}
private void main() {
Class clazz = Dog.class;
Type[] genericInterfaces = clazz.getGenericInterfaces();
Class[] interfaces = clazz.getInterfaces();
}
运行结果
![](/img/245442107557694aef0f07c25be0740187c.jpg)

我们可以看到,clazz.getGenericInterfaces()与clazz.getInterfaces()并没有任何差异。因为 并没有:“实现的接口的Type”

接下来看另一段代码,我们对Eat接口改造一下,增加一个参数化类型

    private class Food&#123;
        String foodName;
    &#125;
    private interface Eat&#123;
        void eat(T things);
    &#125;
    private interface Run&#123;
        void run();
    &#125;

    private class Dog implements Eat,Run&#123;
        @Override
        public void run() &#123; &#125;
        @Override
        public void eat(Food things) &#123; &#125;
    &#125;
    private void main() &#123;
        Class clazz = Dog.class;
        Type[] genericInterfaces = clazz.getGenericInterfaces();
        Class[] interfaces = clazz.getInterfaces();
    &#125;
运行结果: