转自:
下文讲述java代码在运行时,使用反射获取其泛型类型的方法分享,如下所示:
泛型常用于以下两个场景: 1.参数化泛型 2.参数化类
public class MyClass { protected ListstringList = ...; public List getStringList(){ return this.stringList; } } //使用发射 Method method = MyClass.class.getMethod("getStringList", null); Type returnType = method.getGenericReturnType(); if(returnType instanceof ParameterizedType){ ParameterizedType type = (ParameterizedType) returnType; Type[] typeArguments = type.getActualTypeArguments(); for(Type typeArgument : typeArguments){ Class typeArgClass = (Class) typeArgument; System.out.println("typeArgClass = " + typeArgClass); } } -----------运行以上代码,将输出以下信息----- typeArgClass = java.lang.String
public class MyClass { protected ListstringList = ...; public void setStringList(List list){ this.stringList = list; } } method = Myclass.class.getMethod("setStringList", List.class); Type[] genericParameterTypes = method.getGenericParameterTypes(); for(Type genericParameterType : genericParameterTypes){ if(genericParameterType instanceof ParameterizedType){ ParameterizedType aType = (ParameterizedType) genericParameterType; Type[] parameterArgTypes = aType.getActualTypeArguments(); for(Type parameterArgType : parameterArgTypes){ Class parameterArgClass = (Class) parameterArgType; System.out.println("parameterArgClass = " + parameterArgClass); } } } ------运行以上代码,将输出以下信息---- parameterArgType = java.lang.String
public class MyClass { public ListstringList = ...; } Field field = MyClass.class.getField("stringList"); Type genericFieldType = field.getGenericType(); if(genericFieldType instanceof ParameterizedType){ ParameterizedType aType = (ParameterizedType) genericFieldType; Type[] fieldArgTypes = aType.getActualTypeArguments(); for(Type fieldArgType : fieldArgTypes){ Class fieldArgClass = (Class) fieldArgType; System.out.println("fieldArgClass = " + fieldArgClass); } } --------运行以上代码,将输出以下信息----- fieldArgClass = java.lang.String