本文主要是介绍ParameterizedType,getClass(),getGenericSuperclass(),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
子类
public class CustomerDao extends JdbcDaoImpl<Customer>{}
直接父类
‘
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 <T>: 子类需传入的泛型类型. */
public class JdbcDaoImpl<T> implements DAO<T> {private QueryRunner queryRunner = null;private Class<T> type;public JdbcDaoImpl() {queryRunner = new QueryRunner();//getClass()是CustomerDao类type = ReflectionUtils.getSuperGenericType(getClass());}
@Override public List<T> 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<Employee, String>* @param clazz* @param index* @return*/@SuppressWarnings("unchecked")public static Class getSuperClassGenricType(Class clazz, int index){//返回带泛型的父类例如:BaseDao<Employee, String>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];}
}
这篇关于ParameterizedType,getClass(),getGenericSuperclass()的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!