简介Spring 源码是个大宝库,我们能遇到的大部分工具在源码里都能找到,所以笔者开源的 mica 完全基于 Spring 进行基础增强,不重复造轮子。今天我要分享的是在 Spring 中优雅的获取泛型。获取泛型自己解析我们之前的处理方式,代码来源 vjtools(江南白衣)。/** * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. * * 注意泛型必须定义在父类处. 这是唯一可以通过反射从泛型获得Class实例的地方. * * 如无法找到, 返回Object.class. * * 如public UserDao extends HibernateDao<User,Long> * * @param clazz clazz The class to introspect * @param index the Index of the generic declaration, start from 0. * @return the index generic declaration, or Object.class if cannot be determined */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<Integer, List<String>> myMap;public void example() { ResolvableType t = ResolvableType.forField(getClass().getDeclaredField(“myMap”)); t.getSuperType(); // AbstractMap<Integer, List<String>> t.asMap(); // Map<Integer, List<String>> t.getGeneric(0).resolve(); // Integer t.getGeneric(1).resolve(); // List t.getGeneric(1); // List<String> 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…开源推荐Spring boot 微服务高效开发 mica 工具集:https://gitee.com/596392912/micaAvue 一款基于vue可配置化的神奇框架:https://gitee.com/smallweigit/avuepig 宇宙最强微服务(架构师必备):https://gitee.com/log4j/pigSpringBlade 完整的线上解决方案(企业开发必备):https://gitee.com/smallc/SpringBladeIJPay 支付SDK让支付触手可及:https://gitee.com/javen205/IJPay加入【如梦技术】Spring QQ群:479710041,了解更多。关注我们扫描上面二维码,更多精彩内容每天推荐!