`

如何获取父类的泛型的具体类型

阅读更多

问题的关键:clazz其实应该是T.class,clazz该如何获取???

public abstract class BaseDaoImpl<T> implements BaseDao<T>{

  private SessionFactory sessionFactory ;

  //比如Class<User>   clazz ,那么clazz就应该代表User.class 
  private Class<T> clazz ;         //clazz表示该类的子类传递给父类泛型上的类型即T.class  ,我需要在父类上获取父类泛型的具体类型,通过反射

protected BaseDaoImpl(){
   //由于BaseDaoImpls是抽象类,不能实例化,所以this表示子类的实例,那么我就可以利用this来获取父类(BaseDaoImpl)上的泛型的具体类型

  //getGenericSuperclass()方法:获取父类的泛型,返回值是Type类型,Type是Class类的接口,ParameterizedType类用于描述泛型的类,它是jdk升级后新添加的类,专门用来描述泛型

  ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();

  //getActualTypeArguments()方法:获取泛型的真实类型,返回值是Type[]
  clazz = (Class<T>) pt.getActualTypeArguments()[0] ;        

}

public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

public Session getSession(){
  return sessionFactory.getCurrentSession() ;
}

public void save(T entity){

this.getSession().save(entity) ;

} ;

public void update(T entity){
this.getSession().update(entity) ;
} ;

public void delete(Long id){
Object obj = this.getSession().get(clazz, id) ;
this.getSession().delete(obj) ;
} ;

public T getById(Long id){
  return (T) this.getSession().get(clazz, id) ;           //因为Seesion的get方法需要clazz是个Class类型,而且还必须是T.class,所以我要在上面极力获取到T.class
} ;

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics