首页 > 代码库 > 利用反射把ResultSet转换成List
利用反射把ResultSet转换成List
public static List toList(ResultSet rs, Class cls) {
List list = new ArrayList();
try {
// 获取数据库表结构
ResultSetMetaData meta = rs.getMetaData();
Object obj = null;
while (rs.next()) {
// 获取formbean实例对象
obj = Class.forName(cls.getName()).newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (int j = 0; j < fields.length; j++) {
int ci = rs.findColumn(fields[j].getName());
if (ci == -1)
continue;
String methodName = "set" + fields[j].getName();
Method method = obj.getClass().getMethod(methodName,
fields[j].getType());
method.invoke(obj, rs.getObject(ci));
}
list.add(obj);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
return list;
}
}
利用反射把ResultSet转换成List