1 package com.coscon.reflectionTest; 2 3 import java.lang.reflect.Method; 4 import java.lang.reflect.ParameterizedType; 5 import java.lang.reflect.Type; 6 import java.util.List; 7 import java.util.Map; 8 9 //用過反射獲取泛型信息 10 public class ReflectionForGenerics { 11 public void test01(Map<String,User> map,List<User> users){ 12 System.out.println("test01"); 13 } 14 15 public Map<Integer,User> test02(){ 16 System.out.println("test02"); 17 return null; 18 } 19 20 public static void main(String[] args) { 21 try { 22 Class clazz = Class.forName("com.coscon.reflectionTest.ReflectionForGenerics"); 23 //獲得指定方法參數泛型信息 24 Method method = clazz.getMethod("test01", Map.class,List.class); 25 //獲取泛型參數 26 Type[] types = method.getGenericParameterTypes(); 27 for (Type type : types) { 28 System.out.println("#"+type); 29 if(type instanceof ParameterizedType){ 30 Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments(); 31 for (Type type2 : actualTypeArguments) { 32 System.out.println("泛型參數類型:"+type2); 33 } 34 } 35 } 36 37 System.out.println("--------------------------------------------------------------"); 38 Method method2 = clazz.getMethod("test02", null); 39 //獲取返回值泛型信息 40 Type returnType = method2.getGenericReturnType(); 41 System.out.println("#"+returnType); 42 if(returnType instanceof ParameterizedType){ 43 Type[] typeArguments = ((ParameterizedType) returnType).getActualTypeArguments(); 44 for (Type type : typeArguments) { 45 System.out.println("返回值泛型類型:"+type); 46 } 47 } 48 } catch (Exception e) { 49 // TODO Auto-generated catch block 50 e.printStackTrace(); 51 } 52 } 53 }
打印結果
#java.util.Map<java.lang.String, com.coscon.reflectionTest.User>
泛型參數類型:class java.lang.String
泛型參數類型:class com.coscon.reflectionTest.User
#java.util.List<com.coscon.reflectionTest.User>
泛型參數類型:class com.coscon.reflectionTest.User
--------------------------------------------------------------
#java.util.Map<java.lang.Integer, com.coscon.reflectionTest.User>
返回值泛型類型:class java.lang.Integer
返回值泛型類型:class com.coscon.reflectionTest.User