读书人

黑马软件工程师_获取参数类型和泛型的

发布时间: 2012-08-29 08:40:14 作者: rapoo

黑马程序员_获取参数类型和泛型的实际类型参数

?今天学完泛型,最后学到了如何去获得参数类型,这种方法的确是很奇妙,贴出供参考!

public class GenericTest {

public static void main(String[] args) throws Exception {

Method method = GenericTest.class.getMethod("applyVector",??Vector.class, HashMap.class);
??Type[] types = method.getGenericParameterTypes();
??ParameterizedType pType0 = (ParameterizedType) types[0];
??ParameterizedType pType1 = (ParameterizedType) types[1];
??System.out.println(pType0.getRawType());//得到参数的类型
??System.out.println(pType1.getRawType());
??System.out.println(pType1.getActualTypeArguments()[0]);//得到泛型的实际类型参数
??System.out.println(pType1.getActualTypeArguments()[1]);
??System.out.println(method.getReturnType());

?}

?public static void applyVector(Vector<Date> v1, HashMap<String, Integer> map) {
??// 方法中通过参数无法获得参数的类型
??// 但可以通过该方法获得参数的类型及泛型的实际类型参数(反射的方式)
?}

}

最后输出结果为:

class java.util.Vector
class java.util.HashMap
class java.lang.String
class java.lang.Integer
void

注:此方法通过反射得到使用参数的方法包装成Method实例对象,method.getGenericParameterTypes()返回了Method?对象所表示的方法的形参类型,转换在ParameterizedType 类型后,进一步得到了泛型的实际类型参数。

读书人网 >编程

热点推荐