你的位置:首页 > Java教程

[Java教程]通过反射获取泛型信息



 


 

 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 block50       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