java_jdbc_反射技术将查询结果封装为对象

时间:2021-11-01 21:55:13
package cn.itcast.Reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.itcast.JdbcUtils;

//反射获取数据库内容
public class ORMTest {

	public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException, InstantiationException {

		User2 user = (User2)getObject("select id as Id,username as Username,password as Password from t_user where id=1",User2.class);
		System.out.println(user.getUsername());
	}
	
	public static Object getObject(String sql,Class clazz) throws SQLException,
			IllegalAccessException, IllegalArgumentException,
			InvocationTargetException, InstantiationException {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();

			java.sql.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);

			}

			Object obj = null;
			Method[] ms = clazz.getMethods();
			if (rs.next()) {
				obj = clazz.newInstance();
				for (int i = 0; i < colNames.length; i++) {
					String colName = colNames[i];
					String methodName = "set" + colName;
					
					for (Method m : ms) {
						if (methodName.equals(m.getName())) {
							m.invoke(obj, rs.getObject(colName));
						}
					}

				}
			}
			return obj;
		} finally {
			JdbcUtils.free(rs, ps, conn);
		}
	}
}