標籤:style blog http color java io art ar
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