Last active
September 21, 2017 13:12
-
-
Save thinkerzhangyan/8655559c1fbe4afac6792d56f2fb8004 to your computer and use it in GitHub Desktop.
Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Method; | |
import java.lang.reflect.ParameterizedType; | |
import java.lang.reflect.Type; | |
import java.util.Collection; | |
import java.util.Map; | |
public class Test { | |
public static void main(String[] args) throws NoSuchMethodException { | |
Class<?> clazz = Test.class; //取得 Class | |
Method method1 = clazz.getDeclaredMethod("applyCollection1", Collection.class,Map.class); //取得方法 | |
Type[] type1 = method1.getGenericParameterTypes(); //取得泛型类型参数的集合 | |
for(int i=0;i<type1.length;i++){ | |
ParameterizedType ptype = (ParameterizedType)type1[i];//将其转成参数化类型,因为在方法中泛型是参数 | |
Type str = ptype.getRawType(); //取得参数的实际类型 | |
System.out.println("方法参数:"+str); | |
Type[] typeActual = ptype.getActualTypeArguments(); | |
for(int j=0;j<typeActual.length;j++){ | |
System.out.println("泛型参数的实际类型:"+typeActual[j]); | |
} | |
} | |
Method method2 = clazz.getDeclaredMethod("applyCollection2",String.class,Integer.class); //取得方法 | |
//参数里面如果不是参数化类型的话,那么 getGenericParameterTypes就返回与 getParameterTypes 一样 | |
Type[] type2 = method2.getGenericParameterTypes(); | |
Type[] type3 = method2.getParameterTypes(); | |
for(int i=0;i<type2.length;i++){ | |
System.out.println("getGenericParameterTypes方法获得的参数:"+type2[i]); | |
} | |
for(int i=0;i<type2.length;i++){ | |
System.out.println("getParameterTypes方法获得的参数:"+type3[i]); | |
} | |
} | |
//声明一个空的方法,并将泛型用做为方法的参数类型 | |
public void applyCollection1(Collection<Number> collection,Map<String,Integer> msp){ | |
} | |
public void applyCollection2(String str,Integer inVal){ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment