泛型工具类


/**
* 泛型
* 解析父类泛型参数的实际类型
* 解析方法返回值泛型参数的实际类型
*/
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);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值