模拟DBUtils中的queryRunner.query()的反射机制的模拟

本文主要是讲述对于DBUtils中的queryRunner.query(connection,sql, new BeanListHandler<>(Admin.class))的模拟

代码结构:

 DBUtilsReflection类:

/**
 * 将查询到的结果集,运用反射机制,创建对象,并存放如集合中
 * resultSet->admin对象->list集合
 */
public class DBUtilsReflection {
    // 存储admin对象的集合
    private ArrayList<Admin> adminList = new ArrayList<>();
    private ResultSet resultSet = null;
    private PreparedStatement preStatement = null;

    // 利用反射机制,创建对象
    public ArrayList<Admin> getAdminList(Connection connection,String sql,Class<?> aClass){
        try {
            Constructor<?> constructor = aClass.getConstructor(Integer.class, String.class, String.class);
            ResultSet resultSet = getResultSet(connection, sql);
            while(resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String pwd = resultSet.getString("pwd");
                Admin admin = (Admin) constructor.newInstance(id, name, pwd);
                adminList.add(admin);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtilsByDruid.Close(resultSet,preStatement,connection);
        }
        return adminList;
    }

    // 得到它的结果集
    public ResultSet getResultSet(Connection connection,String sql) {

        try {
            preStatement = connection.prepareStatement(sql);
            resultSet = preStatement.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;
    }
}

DBUtilsReflectionTest类:

public class DBUtilsReflectionTest {
    public static void main(String[] args) {
        Connection connection = JDBCUtilsByDruid.getConnection();
        String sql = "select * from admin";
        DBUtilsReflection queryRunner = new DBUtilsReflection();
        ArrayList<Admin> adminList = queryRunner.getAdminList(connection, sql, Admin.class);
        for (Admin admin : adminList) {
            System.out.println(admin);
        }

    }
}

运行结果如下:

Admin{id=3, name='Tom3', pwd='123'}
Admin{id=5, name='Tom2', pwd='123'}
Admin{id=6, name='Tom3', pwd='123'}
Admin{id=8, name='Tom2', pwd='123'}
Admin{id=9, name='Tom3', pwd='123'}
Admin{id=11, name='zw', pwd='123'}
Admin{id=12, name='郑为', pwd='1234'}
Admin{id=13, name='郑威', pwd='1234'}
Admin{id=14, name='郑为', pwd='1234'}
Admin{id=15, name='郑威', pwd='1234'}

Process finished with exit code 0
View Code

 

posted @ 2023-02-01 09:55  zwGitOne  阅读(22)  评论(0编辑  收藏  举报