如何获取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];


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值