先写一个类:
public class Demo03 {
public void test01(Map<String, User> map, List<User> list) {
System.out.println("Demo03.test01()");
}
public Map<Integer, User> test02(){
System.out.println("Demo03.test02()");
return null;
}
}
1、反射获取获取方法参数的泛型类型
// 获取指定方法参数泛型信息
Method m = Demo03.class.getDeclaredMethod("test01", Map.class, List.class);
Type[] genericParameterTypes = m.getGenericParameterTypes();
for (Type type : genericParameterTypes) {
System.out.println("方法参数类型:" + type);
if(type instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
for (Type t : actualTypeArguments) {
System.out.println("--参数泛型类型:" + t);
}
}
}
2、反射获取方法返回值的参数类型
// 获取指定方法返回值泛型信息
Method m2 = Demo03.class.getDeclaredMethod("test02", null);
Type genericReturnType = m2.getGenericReturnType();
if(genericReturnType instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for (Type type : actualTypeArguments) {
System.out.println("方法返回的泛型类型:" + type);
}
}