参考了Retrofit的解析返回类型的代码
- 获取返回类型
Method method = this.getClass().getDeclaredMethod("execute", Request.class, Integer.class);
Type type = method.getGenericReturnType();
- 获取类的泛型参数
@SuppressWarnings("unchecked")
private Class<T> getClassFromInterface(MqttObserver<T> observer) {
try {
Type[] interfaceTypes = observer.getClass().getGenericInterfaces();
Type type;
if (interfaceTypes.length == 0) {
//非接口
type = observer.getClass().getGenericSuperclass();
} else {
type = interfaceTypes[0];
}
if (type == null) {
return null;
}
if (ParameterizedType.class.isAssignableFrom(type.getClass())) {
Type item = (((ParameterizedType) type).getActualTypeArguments())[0];
return ((Class<T>) item);
}
} catch (Exception e) {
return null;
}
return null;
}
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/19392.html