Java泛型 T.class的获取

public interface BaseDao<T> {  
    T get(String id);  
}  
 1 import java.lang.reflect.ParameterizedType;  
 2 import java.lang.reflect.Type;  
 3   
 4 public abstract class HibernateBaseDao<T> implements BaseDao<T> {  
 5     private Class<T> entityClass;  
 6   
 7     /** 
 8      * 这个通常也是hibernate的取得子类class的方法 
 9      *  
10      * @author "yangk" 
11      * @date 2010-4-11 下午01:51:28 
12      */  
13     public HibernateBaseDao() {  
14         Type genType = getClass().getGenericSuperclass();  
15         Type[] params = ((ParameterizedType) genType).getActualTypeArguments();  
16         entityClass = (Class) params[0];  
17     }  
18   
19     @Override  
20     public T get(String id) {  
21         try {  
22             return entityClass.newInstance();  
23         } catch (InstantiationException e) {  
24             // TODO Auto-generated catch block  
25             e.printStackTrace();  
26         } catch (IllegalAccessException e) {  
27             // TODO Auto-generated catch block  
28             e.printStackTrace();  
29         }  
30         return null;  
31     }  
32   
33 }  

14-16行是重点,entityClass即为Class,也就是T.class

 

本文参考:http://blog.csdn.net/ykdsg/article/details/5472591

你可能感兴趣的:(java泛型)