Java获取泛型的Class的工具类
2014-02-08 16:29
357 查看
package com.grape.jxc2.utils;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class GenericsUtils {
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型.
* 如public BookManager extends GenricManager<Book>
*
* @param clazz The class to introspect
* @return the first generic declaration, or <code>Object.class</code> if cannot be determined
*/
@SuppressWarnings("rawtypes")
public static Class getSuperClassGenricType(Class clazz) {
return getSuperClassGenricType(clazz, 0);
}
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型.
* 如public BookManager extends GenricManager<Book>
*
* @param clazz clazz The class to introspect
* @param index the Index of the generic ddeclaration,start from 0.
*/
@SuppressWarnings("rawtypes")
public static Class getSuperClassGenricType(Class clazz, int index) throws IndexOutOfBoundsException {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
return Object.class;
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
}
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class GenericsUtils {
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型.
* 如public BookManager extends GenricManager<Book>
*
* @param clazz The class to introspect
* @return the first generic declaration, or <code>Object.class</code> if cannot be determined
*/
@SuppressWarnings("rawtypes")
public static Class getSuperClassGenricType(Class clazz) {
return getSuperClassGenricType(clazz, 0);
}
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型.
* 如public BookManager extends GenricManager<Book>
*
* @param clazz clazz The class to introspect
* @param index the Index of the generic ddeclaration,start from 0.
*/
@SuppressWarnings("rawtypes")
public static Class getSuperClassGenricType(Class clazz, int index) throws IndexOutOfBoundsException {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
return Object.class;
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
}
相关文章推荐
- Java5泛型的用法,T.class的获取和为擦拭法站台
- java 创建一个Class的对象来获取泛型的class
- java创建一个对象获取泛型的class
- Java获取泛型的Class的工具类
- Java5泛型的用法,T.class的获取和为擦拭法站台
- Java反射通过class获取父类泛型类型
- Java获取泛型T的类型 T.class
- Java | 获取类中所有的泛型对应的class类型
- Java获取泛型的Class对象
- java泛型T.class的获取
- Java5泛型的用法,T.class的获取
- Java通过Class的对象来获取泛型的class示例
- Java通过Class的对象来获取泛型的class示例
- Java通过Class的对象来获取泛型的class示例
- Java获取泛型的Class对象
- java获取泛型的class
- Java反射获取泛型工具类
- Java5泛型的用法,T.class的获取和为擦拭法站台
- 关于Java的泛型在所声明的对象中如何获取class或者实例的方法的总结
- java泛型T.class的获取