通过反射获取泛型参数数组(Class对象 List类型)

来源:互联网 发布:淘宝网秋冬季节短裙子 编辑:程序博客网 时间:2024/06/06 01:32

  /**

* 获取某一个字段上面的泛型参数数组,典型的就是获取List对象里面是啥参数

* @param f
* @return
*/
public static Class<?>[] getParameterizedType(Field f) {


// 获取f字段的通用类型
Type fc = f.getGenericType(); // 关键的地方得到其Generic的类型


// 如果不为空并且是泛型参数的类型
if (fc != null && fc instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) fc;


Type[] types = pt.getActualTypeArguments();


if (types != null && types.length > 0) {
Class<?>[] classes = new Class<?>[types.length];
for (int i = 0; i < classes.length; i++) {
classes[i] = (Class<?>) types[i];
}
return classes;
}
}
return null;
}

0 0
原创粉丝点击