Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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){
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement