泛型工具种
泛型工具类
/** * 泛型 * 解析父类泛型参数的实际类型 * 解析方法返回值泛型参数的实际类型 */ package com.hyb.util.generics; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class GennericsUtil { private static final Log log = LogFactory.getLog(GennericsUtil.class);//需要引入日志包 /** * * 通过反射获取指定类的父类泛型参数的实际类型, * 如XXXDao extends BaseDao<Integer>中得到Integer的类型 * @param clazz 需要找出其父类泛型参数的类 * @param index 参数下标 * @return 返回对应参数类型对象 */ public static Class<?> getSuperGenericsType(Class<?> clazz, int index) { Type gType = clazz.getGenericSuperclass(); //返回clazz对象的的父类的 Type if(!(gType instanceof ParameterizedType)) { //查看gType是否是ParameterizedType类型,如不是,则不支持泛型 log.info(clazz.getName() + "的父类不是ParameterizedType类型"); return Object.class; } Type[] gParamsType = ((ParameterizedType)gType).getActualTypeArguments(); //返回表示此类型实际类型参数的 Type 对象的数组BaseDao<Integer>中的Integer if(index < 0 || index >= gParamsType.length) { log.info("参数index越界或者有错!"); return Object.class; } if(!(gParamsType[index] instanceof Class<?>)) { return Object.class; } return (Class<?>)gParamsType[index]; //返回该泛型参数对象 } /** * * 通过反射获取指定类的父类泛型参数的实际类型, * 如XXXDao extends BaseDao<Integer>中得到Integer的类型 * @param clazz 需要找出其父类泛型参数的类 * @return 返回第一个参数类型对象 */ public static Class<?> getSuperGenericsType(Class<?> clazz) { return getSuperGenericsType(clazz, 0); } /** * * 通过反射获取指定的方法返回值泛型参数的实际类型, * 如Map<String, String> getMap()中得到String的类型 * @param method 指定的方法 * @param index * @return 返回参数实际类型对象 */ public static Class<?> getMethodReturnGenericType(Method method, int index) { Type rType = method.getGenericReturnType();//method对象所表示方法的实际返回类型的 Type对象 if(!(rType instanceof ParameterizedType)) { return Object.class; } Type[] rParamsType = ((ParameterizedType)rType).getActualTypeArguments();//返回表示此类型实际类型参数的 Type对象的数组,如Map<String, String>中的String if(index < 0 || index >= rParamsType.length) { log.info("参数index越界或者有错!"); return Object.class; } if(!(rParamsType[index] instanceof Class<?>)) { return Object.class; } return (Class<?>)rParamsType[index]; } /** * * 通过反射获取指定的方法返回值泛型参数的实际类型, * 如Map<String, String> getMap()中得到String的类型 * @param method * @return 返回第一个参数实际类型 */ public static Class<?> getMethodReturnGenericType(Method method) { return getMethodReturnGenericType(method, 0); } }