Method method = clazz.getDeclaredMethod("applyCollection", Collection.class); //取得方法
Type[] type = method.getGenericParameterTypes(); //取得泛型类型参数集
ParameterizedType ptype = (ParameterizedType)type[0];//将其转成参数化类型,因为在方法中泛型是参数,且Number是第一个类型参数
type = ptype.getActualTypeArguments(); //取得参数的实际类型
System.out.println(type[0]); //取出第一个元素
} catch (Exception e) {
e.printStackTrace();
}
}
//声明一个空的方法,并将泛型用做为方法的参数类型
public void applyCollection(Collection
}
}
后台打印输出的结果:
class java.lang.Number
通过字段变量,反射获得泛型的实际类型参数:
package test;www.2cto.com
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Map;
/**
* -----------------------------------------
* @描述 测试类
* @作者 fancy
* @邮箱 fancydeepin@yeah.net
* @日期 2012-8-26
* -----------------------------------------
*/
public class Test {
private Map
public static void main(String[] args){
try {
Class< > clazz = Test.class; //取得 Class
Field field = clazz.getDeclaredField("collection"); //取得字段变量
Type type = field.getGenericType(); //取得泛型的类型
ParameterizedType ptype = (ParameterizedType)type; //转成参数化类型
System.out.println(ptype.getActualTypeArguments()[0]); //取出第一个参数的实际类型
System.out.println(ptype.getActualTypeArguments()[1]); //取出第二个参数的实际类型
} catch (Exception e) {
e.printStackTrace();
}
}
}
后台打印输出的结果:
class java.lang.String
class java.lang.Number