《Java架构筑基》从Java基础讲起——泛型与反射

通过反射获得泛型的实际类型参数

把泛型变量当成方法的参数,利用Method类的getGenericParameterTypes方法来获取泛型的实际类型参数

例子:

public class GenericTest {
    public static void main(String[] args) throws Exception {
        getParamType();
    }
    /*利用反射获取方法参数的实际参数类型*/
    public static void getParamType() throws NoSuchMethodException{
        Method method = GenericTest.class.getMethod("applyMap",Map.class);
        //获取方法的泛型参数的类型
        Type[] types = method.getGenericParameterTypes();
        System.out.println(types[0]);
        //参数化的类型
        ParameterizedType pType  = (ParameterizedType)types[0];
        //原始类型
        System.out.println(pType.getRawType());
        //实际类型参数
        System.out.println(pType.getActualTypeArguments()[0]);
        System.out.println(pType.getActualTypeArguments()[1]);
    }
    /*供测试参数类型的方法*/
    public static void applyMap(Map<Integer,String> map){
    }
}

输出结果:

java.util.Map<java.lang.Integer, java.lang.String>
    interface java.util.Map
    class java.lang.Integer
    class java.lang.String

猜你喜欢

转载自blog.51cto.com/14637764/2462214