"Java-based build a shelf," we start from the basics of Java - generics and reflection

Generic type parameter is obtained by reflecting the actual

The generic variables as parameters of the method, the method using Method getGenericParameterTypes generic class to obtain the actual type arguments

example:

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){
    }
}

Output:

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

Guess you like

Origin blog.51cto.com/14637764/2462214