研究BeanHandler,很好奇怎么实现的,从网上找到一个代码,先Mark一下,出处地址:https://blog.youkuaiyun.com/weixin_36328444/article/details/80406057
public class BeanHandler<T> implements ResultSetHandler<T> {
private Class<T> classType; //把结果集的一行数据封装成什么类型的对象
public BeanHandler(Class<T> classType) {
this.classType=classType;
}
public T handle(ResultSet rs) throws Exception {
//1)创建对应类的一个对象
T obj=classType.newInstance();
//2)取出结果集中当前光标所在行的某一列数据
BeanInfo beanInfo=Introspector.getBeanInfo(classType, Object.class);
PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();
if(rs.next()) {
for(PropertyDescriptor pd:pds) {
String columnName=pd.getName(); //获取对象的属性名,属性名和列名相同
Object val=rs.getObject(columnName);
//3)调用该对象的setter方法,把某一列的数据设置进去
pd.getWriteMethod().invoke(obj, val);
}
}
return obj;
}
}