如何获取java中泛型参数的实际类型

package cn.itcast.oa.base.impl;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import java.util.List;import javax.annotation.Resource;import org.hibernate.Session;import org.hibernate.SessionFactory;import cn.itcast.oa.base.BaseDao;/** * 以下方法无需关注事务,因为spring将为我们管理事务 * @author Administrator * * @param <T> */public class BaseDaoImpl<T> implements BaseDao<T> {@Resource //此类将作为父类使用,,所以不需要在类上加注解,将其引入容器。当子类继承该类时,sessionFactory也将注入private SessionFactory sessionFactory;private Class<T> clazz;//获取实际实体类型@SuppressWarnings("unchecked")public BaseDaoImpl(){//this.getClass():当前类的类型//this.getClass().getGenericSuperclass():获取当前new对象的泛型父类Type t=this.getClass().getGenericSuperclass();//获取泛型参数的实际类型this.clazz=(Class<T>)((ParameterizedType)t).getActualTypeArguments()[0];}/** * 获取当前存在的session * 此处设置为protected,方便子类使用 * @return */protected Session getSession() {return sessionFactory.getCurrentSession();}public void save(T entity) {getSession().save(entity);}public void delete(Long id) {Object obj=getById(id);if(obj!=null){getSession().delete(obj);}}public T getById(Long id) {getSession().get(clazz, id);return null;}@SuppressWarnings("unchecked")public List<T> getByIds(Long[] ids) {return getSession().createQuery("FROM "+clazz.getSimpleName()+" WHERE id IN (:ids)").setParameterList("ids", ids).list();}@SuppressWarnings("unchecked")public List<T> findAll() {return getSession().createQuery("FROM "+clazz.getSimpleName()).list();}public void update(T entity) {getSession().update(entity);}}

在以上分装的通用方法中,某些方法需要传入实体的实际类型,此时可通过以下代码获取

//this.getClass():当前类的类型//this.getClass().getGenericSuperclass():获取当前类的泛型父类Type t=this.getClass().getGenericSuperclass();//获取泛型参数的实际类型this.clazz=(Class<T>)((ParameterizedType)t).getActualTypeArguments()[0];

在旅途中,我遇见了你,你我相识是缘分!看着你手中的戒指,

如何获取java中泛型参数的实际类型

相关文章:

你感兴趣的文章:

标签云: