简介
Spring 源码是个大宝库,我们能遇到的大部分工具在源码里都能找到,所以笔者开源的 mica 完全基于 Spring 进行基础增强,不重复造轮子。今天我要分享的是在 Spring 中优雅的获取泛型。
获取泛型
自己解析
我们之前的处理方式,代码来源 vjtools(江南白衣)。
public static Class getClassGenericType(final Class clazz, final int index) {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if ((index >= params.length) || (index < 0)) {
logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
+ params.length);
return Object.class;
}
if (!(params[index] instanceof Class)) {
logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
return Object.class;
}
return (Class) params[index];
}
ResolvableType 工具
从 Spring 4.0 开始 Spring 中添加了 ResolvableType 工具,这个类可以更加方便的用来回去泛型信息。
首先我们来看看官方示例:
private HashMap> myMap; public void example() { ResolvableType t = ResolvableType.forField(getClass().getDeclaredField("myMap")); t.getSuperType(); // AbstractMap > t.asMap(); // Map > t.getGeneric(0).resolve(); // Integer t.getGeneric(1).resolve(); // List t.getGeneric(1); // List t.resolveGeneric(1, 0); // String }
详细说明
构造获取 Field 的泛型信息
ResolvableType.forField(Field)
构造获取 Method 的泛型信息
ResolvableType.forMethodParameter(Method, int)
构造获取方法返回参数的泛型信息
ResolvableType.forMethodReturnType(Method)
构造获取构造参数的泛型信息
ResolvableType.forConstructorParameter(Constructor, int)
构造获取类的泛型信息
ResolvableType.forClass(Class)
构造获取类型的泛型信息
ResolvableType.forType(Type)
构造获取实例的泛型信息
ResolvableType.forInstance(Object)
更多使用 Api 请查看,ResolvableType java doc: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/ResolvableType.html
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



