【转】泛型T类型的获取
转自:http://blog.csdn.net/running_snail_/article/details/7077947
5 /** 6 * 可以在service层直接调用,也可以在DAO层扩展调用 7 */ 8 public class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK>{ 9 10 // ... 11 12 private Class<T> persistentClass; 13 /** 14 * 用于Dao层子类使用的构造函数. 通过子类的泛型定义取得对象类型 15 */ 16 17 @SuppressWarnings("unchecked") 18 public BaseDaoImpl(){ 19 //getClass() 返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的超类的 Class。 20 this.persistentClass=(Class<T>)getSuperClassGenricType(getClass(), 0); 21 } 22 23 /** 24 * 通过反射, 获得定义Class时声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. 25 * 26 *@param clazz 27 * clazz The class to introspect 28 * @param index 29 * the Index of the generic ddeclaration,start from 0. 30 * @return the index generic declaration, or Object.class if cannot be 31 * determined 32 */ 33 @SuppressWarnings("unchecked") 34 public static Class<Object> getSuperClassGenricType(final Class clazz, final int index) { 35 36 //返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。 37 Type genType = clazz.getGenericSuperclass(); 38 39 if (!(genType instanceof ParameterizedType)) { 40 return Object.class; 41 } 42 //返回表示此类型实际类型参数的 Type 对象的数组。 43 Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); 44 45 if (index >= params.length || index < 0) { 46 return Object.class; 47 } 48 if (!(params[index] instanceof Class)) { 49 return Object.class; 50 } 51 52 return (Class) params[index]; 53 }
在创建具体的BaseDaoImpl对象的时候指定了具体的泛型类型(比如Person),所以在实例化时通过调用 clazz.getGenericSuperclass() 得到的 genType 就是第一个泛型类型是 Person 的 Base.class;
此时 将它强转成泛型类型调用获取参数的方法 ((ParameterizedType)genType).getActuallTypeArguments() 得到的就是一个 Type[] params = [Person.class, PK.class] (第二个元素是指定的类型在此未具体写);
所以 (Class)params[0] 自然就是 Person.class 啦。
博主 running_snail_ 的代码中考虑了非泛型类型的情况返回Object.class,因此这是一个通用的方法,挺棒!

浙公网安备 33010602011771号