其他分享
首页 > 其他分享> > 十二、反射操作泛型

十二、反射操作泛型

作者:互联网

 

public class Demo10 {

    public void m1(Map<String, User> map, LinkedList<User> list, String msg) {
        System.out.println("hello");
    }


    public Map<String, User> m2() {
        return  null;
    }

    public static void main(String[] args) throws NoSuchMethodException {
        Class clazz = Demo10.class;
        Method m1 = clazz.getMethod("m1", Map.class, LinkedList.class, String.class);

        //获取方法中参数的泛型
        Type[] genericParameterTypes = m1.getGenericParameterTypes();
        for (Type  genericParameterType: genericParameterTypes) {
            System.out.print(genericParameterType+":    ");
            //单独打印类型
            if (genericParameterType instanceof ParameterizedType){
                Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {
                    System.out.print(actualTypeArgument+"    ");
                }
            }
            System.out.println();
        }

        
        System.out.println("================================");
        Method m2 = clazz.getMethod("m2");
        //获取方法中返回值的泛型
        Type type = m2.getGenericReturnType();
        System.out.print(type);
        if (type instanceof ParameterizedType){
            Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
            for (Type actualTypeArgument : actualTypeArguments) {
                System.out.print(actualTypeArgument+"    ");
            }
        }
    }
}

 

标签:反射,十二,System,类型,泛型,ParameterizedType,Type,out
来源: https://www.cnblogs.com/epiphany8/p/16367291.html