ParameterizedType,getClass(),getGenericSuperclass()

子类

public class CustomerDao 
	extends JdbcDaoImpl{
	
}

直接父类

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

/**
 * 使用 QueryRunner 提供其具体的实现
 * @param : 子类需传入的泛型类型. 
 */
public class JdbcDaoImpl implements DAO {

	private QueryRunner queryRunner = null;
	private Class type;
	
	public JdbcDaoImpl() {
		queryRunner = new QueryRunner();
		//getClass()是CustomerDao类
		type = ReflectionUtils.getSuperGenericType(getClass());
	}
@Override 
	public List getForList(Connection connection, String sql, Object... args) 
			throws SQLException {
		return queryRunner.query(connection, sql, 
				new BeanListHandler<>(type), args);
	}
}
超父类

public class ReflectionUtils {

	
	/**
	 * 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型
	 * 如: public EmployeeDao extends BaseDao
	 * @param clazz
	 * @param index
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Class getSuperClassGenricType(Class clazz, int index){
		
		//返回带泛型的父类例如:BaseDao
		Type genType = clazz.getGenericSuperclass();
		
		//ParameterizedType代表带泛型的类

		if(!(genType instanceof ParameterizedType)){
			return Object.class;
		}
		//获取类似Employee,String泛型的类型
		Type [] params = ((ParameterizedType)genType).getActualTypeArguments();
		
		if(index >= params.length || index < 0){
			return Object.class;
		}
		
		if(!(params[index] instanceof Class)){
			return Object.class;
		}
		
		return (Class) params[index];
	}
}


你可能感兴趣的:(Java基础知识)