需求场景:为什么需要获取泛型类型?
运行时获取泛型,涉及泛型的对象的序列化/反序列化上
java选择的泛型方式是类型擦除式泛型,就是直接把已有的类型泛型化,不需要改变字节码,不需要改动JVM
如何获取泛型方法的泛型?
1.反射
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public static void getMethodReturnType() throws Exception{ Method method=MyClass.class.getMethod("getStringList",null); System.out.println(method.getReturnType()); Type retrunType=method.getGenericReturnType(); System.out.println(retrunType); if(retrunType instanceof ParameterizedType){ ParameterizedType type=(ParameterizedType)retrunType; Type[] typeArguments=type.getActualTypeArguments(); for(Type typeArgument:typeArguments){ Class typeArgClass=(Class)typeArgument; System.out.println("泛型类型:"+typeArgClass); } } }
public static <T> T[] convert (List<T> list,Class<T> compoentType){ (T[])Array.newInstance(compoentType,List.size())) }
@Test public void test01() { ParameterizedType genericSuperclass = (ParameterizedType) Student.class.getGenericSuperclass(); System.out.println(genericSuperclass); Type type = genericSuperclass.getActualTypeArguments()[0]; System.out.println(type); System.out.println(); }
|
2.更优雅地获取泛型方法
Spring ResolvableType 官方API
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/ResolvableType.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public void test04() { ResolvableType resolvableType = ResolvableType.forClass(Student.class); System.out.println(resolvableType); Class<?> resolve = resolvableType.getSuperType().getGeneric(0).resolve(); System.out.println(resolve); }
构造获取 Field 的泛型信息 ResolvableType.forField(Field) 构造获取 Method 的泛型信息 ResolvableType.forMethodParameter(Method, int) 构造获取方法返回参数的泛型信息 ResolvableType.forMethodReturnType(Method) 构造获取构造参数的泛型信息 ResolvableType.forConstructorParameter(Constructor, int) 构造获取类的泛型信息 ResolvableType.forClass(Class) 构造获取类型的泛型信息 ResolvableType.forClass(Class) 构造获取实例的泛型信息 ResolvableType.forInstance(Object)
|