public class ORMTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public static Object getUser(String sql, Class clazz) throws Exception {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Object obj = null;
try {
conn = JdbcUtils.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
String[] colNames = new String[count];
for (int i=1; i<=count; i++) {
colNames[i-1] = rsmd.getColumnLabel(i);
}
Method[] ms = obj.getClass().getMethods();
if (rs.next()) {
obj = clazz.newInstance();
for (int i=0; i<colNames.length; i++) {
String colName = colNames[i];
String methodName = "set" + colName;
// Method method = user.getClass().getMethod(methodName, String.class);
// method.invoke(user, rs.getObject(colName));
for (Method m : ms) {
if (m.getName().equals(methodName)) {
m.invoke(obj, rs.getObject(colName));
}
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return obj;
}
}
Java反射将Jdbc查询结果封装为对象
最新推荐文章于 2019-05-20 10:23:06 发布