泛型T的类型获取

T.getClass()或者T.class都是非法的,因为T是泛型变量。

由于一个类的类型是什么是在编译期处理的,故不能在运行时直接在Base里得到T的实际类型。


  1. /** 
  2.  *@author Joshua 
  3.  *@version 2011-12-15 下午02:27:43 
  4.  */  
  5. /** 
  6.  * 可以在service层直接调用,也可以在DAO层扩展调用 
  7.  */  
  8. public class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK>{  

...

  1.     private Class<T> persistentClass;  
  2.    /** 
  3.     * 用于Dao层子类使用的构造函数. 通过子类的泛型定义取得对象类型 
  4.     */  
  5.   
  6. @SuppressWarnings("unchecked")  
  7. public BaseDaoImpl(){  
  8.     //getClass() 返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的超类的 Class。  
  9.     this.persistentClass=(Class<T>)getSuperClassGenricType(getClass(), 0);  
  10. }  

...


  1. /** 
  2.      * 通过反射, 获得定义Class时声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. 
  3.      *  
  4.      *@param clazz 
  5.      *            clazz The class to introspect 
  6.      * @param index 
  7.      *            the Index of the generic ddeclaration,start from 0. 
  8.      * @return the index generic declaration, or Object.class if cannot be 
  9.      *         determined 
  10.      */  
  11.     @SuppressWarnings("unchecked")  
  12.     public static Class<Object> getSuperClassGenricType(final Class clazz, final int index) {  
  13.           
  14.         //返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。  
  15.         Type genType = clazz.getGenericSuperclass();  
  16.   
  17.         if (!(genType instanceof ParameterizedType)) {  
  18.            return Object.class;  
  19.         }  
  20.         //返回表示此类型实际类型参数的 Type 对象的数组。  
  21.         Type[] params = ((ParameterizedType) genType).getActualTypeArguments();  
  22.   
  23.         if (index >= params.length || index < 0) {  
  24.                      return Object.class;  
  25.         }  
  26.         if (!(params[index] instanceof Class)) {  
  27.               return Object.class;  
  28.         }  
  29.   
  30.         return (Class) params[index];  
  31.     } 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值