Java获取泛型的Class对象

工作中瞄到的,在此收集了

[java] view plain copy
 
  1. public class RawDao<T> {  
  2.     protected Class<T> clazz;  
  3.   
  4.     @SuppressWarnings("unchecked")  
  5.     public RawDao() {  
  6.         @SuppressWarnings("rawtypes")  
  7.         Class clazz = getClass();  
  8.   
  9.         while (clazz != Object.class) {  
  10.             Type t = clazz.getGenericSuperclass();  
  11.             if (t instanceof ParameterizedType) {  
  12.                 Type[] args = ((ParameterizedType) t).getActualTypeArguments();  
  13.                 if (args[0] instanceof Class) {  
  14.                     this.clazz = (Class<T>) args[0];  
  15.                     break;  
  16.                 }  
  17.             }  
  18.             clazz = clazz.getSuperclass();  
  19.         }  
  20.     }  
posted @ 2016-02-18 11:12  牧之丨  阅读(16986)  评论(1编辑  收藏  举报