/**
* 从ResultSet绑定到JavaBean
*
* @param ResultSet
* @param DTO(JavaBean)
* @return DTO
*/
public static DTO bindDataToDTO(ResultSet rs, DTO dto) throws Exception {
//取得Method方法
Method[] methods = dto.getClass().getMethods();
//取得ResultSet的列名
ResultSetMetaData rsmd = rs.getMetaData();
int columnsCount = rsmd.getColumnCount();
String[] columnNames = new String[columnsCount];
for (int i = 0; i < columnsCount; i++) {
columnNames[i] = rsmd.getColumnLabel(i + 1);
}
//遍历ResultSet
while (rs.next()) {
//反射, 从ResultSet绑定到JavaBean
for (int i = 0; i < columnNames.length; i++) {
//取得Set方法
String setMethodName = "set" + columnNames[i];
//遍历Method
for (int j = 0; j < methods.length; j++) {
if (methods[j].getName().equalsIgnoreCase(setMethodName)) {
setMethodName = methods[j].getName();
Object value = rs.getObject(columnNames[i]);
//实行Set方法
try {
//JavaBean内部属性和ResultSet中一致时候
Method setMethod = dto.getClass().getMethod(
setMethodName, value.getClass());
setMethod.invoke(dto, value);
} catch (Exception e) {
//JavaBean内部属性和ResultSet中不一致时候,使用String来输入值。
Method setMethod = dto.getClass().getMethod(
setMethodName, String.class);
setMethod.invoke(dto, value.toString());
}
}
}
}
}
return dto;
}