package 反射与注解; import 反射与注解.POJO.User; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import java.util.Map; public class 泛型反射 { public void test01(Map<String, User> map, List<User> list) { System.out.println("test01"); } public List<User> test02() { System.out.println("test02"); return null; } public static void main(String[] args) throws NoSuchMethodException { System.out.println("======================================test01======================================"); Method test01 = 泛型反射.class.getMethod("test01", Map.class, List.class); Type[] genericParameterTypes = test01.getGenericParameterTypes(); // 获取泛型反射类型 for (Type genericParameterType : genericParameterTypes) { System.out.println("#" + genericParameterType); // 获取实际泛型里面的类型 if (genericParameterType instanceof ParameterizedType) { Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments(); // 获取真实参数类型 for (Type actualTypeArgument : actualTypeArguments) { System.out.println("$" + actualTypeArgument); } } } System.out.println("======================================test02======================================"); Method tes02 = 泛型反射.class.getMethod("test02"); Type genericReturnType = tes02.getGenericReturnType();// 获取泛型反射类型 System.out.println("#" + genericReturnType); // 获取实际泛型里面的类型 if (genericReturnType instanceof ParameterizedType) { Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments(); // 获取真实参数类型 for (Type actualTypeArgument : actualTypeArguments) { System.out.println("$" + actualTypeArgument); } } } }
输出结果