자바 반사 Jdbc 조회 결 과 를 대상 으로 패키지

1489 단어 자바 반사

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;
	}
}

좋은 웹페이지 즐겨찾기