反射3:利用java反射技术将查询结果封装成对象

时间:2021-05-05 21:56:49
package cn.itcast.domain;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

import cn.itcast.jdbc.JdbcUtils;

public class ORMTest {

    public static void main(String[] args) throws Exception {
        User user = getUser("select id as Id , name as Name , birthday as Birthday , money as Money from user where id = 1");
        System.out.println(user);
    }

    // 将数据库中读出的数据放到新建的User对象中,返回User对象
    static User getUser(String sql) throws Exception {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = 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.getColumnName(i);
            }

            User user = null;

            while (rs.next()) {
                user = new User();
                Method[] ms = user.getClass().getMethods();
                for (int i = 0; i < colNames.length; i++) {
                    String colName = colNames[i];
                    String methodName = "set" + colName; // set方法的名字
                    for (Method m : ms) {
                        if (methodName.equals(m.getName()))
                            m.invoke(user, rs.getObject(colName));
                    }
                }
            }
            return user;
        } finally {
            JdbcUtils.free(rs, ps, conn);
        }
    }
}