泛型 第二篇 反射操作泛型

  • 四大对象
  • ParameterizedType:表示一种参数化的类型,比如Collection< String >
  • GenericArrayType:表示一种元素类型是参数化类型或者类型变量的数组类型
  • TypeVariable:是各种类型变量的公共父接口
  • WildcardType:代表一种通配符类型表达式,比如?、? extends Number、? super Integer。(wildcard是一个单词:就是”通配符“)

设计的api

//获取类对应的Class对象1 Class cls = Object.class;

//获取类的成员变量2 Field flild = cls.getDeclaredField("");

//获取成员变量的数据类型(普通)3 Class<?> type = field.getType();

////获取成员变量的数据类型(泛型)4 Type gType = field.getGenericType();

还要强转为if (gType instanceof ParameterizedType){

ParameterizedType pType = (ParameterizedType) gType;

//获取泛型的参数类型(String,Integer)

5 Type[] tArgs = pType.getActualTypeArguments();

//返回没有泛型信息的原始类型(Map)

6 Type rType = pType.getRawType()


实例一

获取成员变量的泛型

public class tianxiaopeng {

//泛型类型参数类型 private Map<String,Integer> sco;

//普通类型参数类型 private int gra;

  //定义两个带泛型的方法
    public void zhouranran(Map<String,Person> map,List<Person> list){
        System.out.println("Demo.test01()");
    }   
    public Map<Integer,Person> wangmingming(){
        System.out.println("Demo.test02()");
        return null;
    }   
}


1、获得对象的class对象 cls          //2 获取Sco的成员变量
         Field field = cls.getDeclaredField("sco");
         //3 获取成员变量的泛型类型
         Type type = field.getGenericType();
         //4 强制转换为ParameterizedType
         if (type instanceof ParameterizedType){
             ParameterizedType pType = (ParameterizedType) type;
            //5 获取泛型类型参数
             Type[] tArgs = pType.getActualTypeArguments();
             for (Type t:tArgs){
                 System.out.println(t);

             }


获取方法的上面的泛型

  //获得指定方法参数泛型信息
    Method m = Demo.class.getMethod("zhouranran", Map.class,List.class);
    Type[] t = m.getGenericParameterTypes();
    for (Type paramType : t) {
        System.out.println("#"+paramType);
        if(paramType instanceof ParameterizedType){
            //获取泛型中的具体信息
            Type[] genericTypes = ((ParameterizedType) paramType).getActualTypeArguments();
            for (Type genericType : genericTypes) {
                System.out.println("泛型类型:"+genericType);
            }
        }
    }   

    //获得指定方法返回值泛型信息
    Method m2 = Demo.class.getMethod("wangmingming", null);
    Type returnType = m2.getGenericReturnType();
    if(returnType instanceof ParameterizedType){
            Type[] genericTypes = ((ParameterizedType) returnType).getActualTypeArguments();
            for (Type genericType : genericTypes) {
                System.out.println("返回值,泛型类型:"+genericType);
            }                   
    }    

获得类上面的泛型

public static Type[] getParameterizedTypes(Object object) {
    Type superclassType = object.getClass().getGenericSuperclass();
    if (!ParameterizedType.class.isAssignableFrom(superclassType.getClass())) {
        return null;
    }
    return ((ParameterizedType)superclassType).getActualTypeArguments();
}

猜你喜欢

转载自blog.csdn.net/yz18931904/article/details/80523380