通过反射来获取泛型的参数以及返回值(不是很懂)

反射获取泛型有下面的方法
1.从方法中获取泛型参数列表
Type[] genericParameterTypes = method.getGenericParameterTypes ();
2.

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
public class Test08 {
    public void test01(Map<String,User> map, List<User> list){
        System.out.println ("test01");
    }
    public Map<String,User> test02(){
        System.out.println ("test02");
        return null;
    }
    public static void main(String[] args) throws NoSuchMethodException {
        //首先获取test01方法
        Method method = Test08.class.getMethod ("test01",Map.class,List.class);
        //将方法的泛型参数类型存储在Type类型数组,type类型可以存储所有的java类型
        Type[] genericParameterTypes = method.getGenericParameterTypes ();
        for (Type genericParameterType : genericParameterTypes) {
            //获取泛型及其中参数
            System.out.println ("##"+genericParameterType);
            //
            if(genericParameterType instanceof ParameterizedType){
                Type[] actuallyTypeArguments = ((ParameterizedType)genericParameterType).getActualTypeArguments();
                for (Type actuallyTypeArgument : actuallyTypeArguments) {
                    System.out.println (actuallyTypeArgument);
                }
            }
        }
        System.out.println ("--------------------------------");
        method = Test08.class.getMethod ("test02",null);
        Type genericReturnType = method.getGenericReturnType ();
        if(genericReturnType instanceof ParameterizedType){
            Type[] actuallyTypeArguments = ((ParameterizedType)genericReturnType).getActualTypeArguments();
            for (Type actuallyTypeArgument : actuallyTypeArguments) {
                System.out.println (actuallyTypeArgument);
            }
        }

    }
}
结果:
##java.util.Map<java.lang.String, Reflection.User>
class java.lang.String
class Reflection.User
##java.util.List<Reflection.User>
class Reflection.User
--------------------------------
class java.lang.String
class Reflection.User
posted @ 2020-04-21 09:08  li33的博客  阅读(1233)  评论(0编辑  收藏  举报