Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. import java.lang.reflect.Method;
  2. import java.lang.reflect.ParameterizedType;
  3. import java.lang.reflect.Type;
  4. import java.util.Collection;
  5. import java.util.Map;
  6.  
  7. public class Test {
  8.  
  9. public static void main(String[] args) throws NoSuchMethodException {
  10.  
  11. Class<?> clazz = Test.class; //取得 Class
  12.  
  13. Method method1 = clazz.getDeclaredMethod("applyCollection1", Collection.class,Map.class); //取得方法
  14. Type[] type1 = method1.getGenericParameterTypes(); //取得泛型类型参数的集合
  15.  
  16. for(int i=0;i<type1.length;i++){
  17. ParameterizedType ptype = (ParameterizedType)type1[i];//将其转成参数化类型,因为在方法中泛型是参数
  18. Type str = ptype.getRawType(); //取得参数的实际类型
  19. System.out.println("方法参数:"+str);
  20. Type[] typeActual = ptype.getActualTypeArguments();
  21. for(int j=0;j<typeActual.length;j++){
  22. System.out.println("泛型参数的实际类型:"+typeActual[j]);
  23. }
  24. }
  25.  
  26. Method method2 = clazz.getDeclaredMethod("applyCollection2",String.class,Integer.class); //取得方法
  27. //参数里面如果不是参数化类型的话,那么 getGenericParameterTypes就返回与 getParameterTypes 一样 
  28. Type[] type2 = method2.getGenericParameterTypes();
  29. Type[] type3 = method2.getParameterTypes();
  30. for(int i=0;i<type2.length;i++){
  31. System.out.println("getGenericParameterTypes方法获得的参数:"+type2[i]);
  32. }
  33. for(int i=0;i<type2.length;i++){
  34. System.out.println("getParameterTypes方法获得的参数:"+type3[i]);
  35. }
  36. }
  37.  
  38. //声明一个空的方法,并将泛型用做为方法的参数类型
  39. public void applyCollection1(Collection<Number> collection,Map<String,Integer> msp){
  40. }
  41.  
  42. public void applyCollection2(String str,Integer inVal){
  43. }
  44.  
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement