package com.jdbc; public class User { private Integer id; private String name; private Integer age; @Override public String toString() { return "User{" + "id=" + id + ", name=‘" + name + ‘\‘‘ + ", age=" + age + ‘}‘; } }
package com.jdbc; import java.lang.reflect.*; /** * 反射工具类,访问私有变量, 获取泛型类型 Class, 提取集合中元素属性等 Utils 函数 */ public class ReflectionUtils { /** * 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型 * 如: public EmployeeDao extends BaseDao<Employee, String> */ @SuppressWarnings("unchecked") public static Class getSuperClassGenricType(Class clazz, int index) { Type genType = clazz.getGenericSuperclass(); if (!(genType instanceof ParameterizedType)) { return Object.class; } Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (index >= params.length || index < 0) { return Object.class; } if (!(params[index] instanceof Class)) { return Object.class; } return (Class) params[index]; } /** * 通过反射, 获得 Class 定义中声明的父类的泛型参数类型 * 如: public EmployeeDao extends BaseDao<Employee, String> */ @SuppressWarnings("unchecked") public static <T> Class<T> getSuperGenericType(Class clazz) { return getSuperClassGenricType(clazz, 0); } /** * 循环向上转型, 获取对象的 DeclaredMethod */ public static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes) { for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) { try { //superClass.getMethod(methodName, parameterTypes); return superClass.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { //Method 不在当前类定义, 继续向上转型 } } return null; } /** * 使 filed 变为可访问 */ public static void makeAccessible(Field field) { if (!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } } /** * 循环向上转型, 获取对象的 DeclaredField */ public static Field getDeclaredField(Object object, String filedName) { for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) { try { return superClass.getDeclaredField(filedName); } catch (NoSuchFieldException e) { //Field 不在当前类定义, 继续向上转型 } } return null; } /** * 直接调用对象方法, 忽略修饰符(private, protected) */ public static Object invokeMethod(Object object, String methodName, Class<?>[] parameterTypes, Object[] parameters) throws InvocationTargetException { Method method = getDeclaredMethod(object, methodName, parameterTypes); if (method == null) { throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]"); } method.setAccessible(true); try { return method.invoke(object, parameters); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } /** * 直接设置对象属性值, 忽略 private/protected 修饰符与 setter */ public static void setFieldValue(Object object, String fieldName, Object value) { Field field = getDeclaredField(object, fieldName); if (field == null) throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]"); makeAccessible(field); try { field.set(object, value); } catch (IllegalAccessException e) { e.printStackTrace(); } } /** * 直接读取对象的属性值, 忽略 private/protected 修饰符与 setter */ public static Object getFieldValue(Object object, String fieldName) { Field field = getDeclaredField(object, fieldName); if (field == null) throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]"); makeAccessible(field); Object result = null; try { result = field.get(object); } catch (IllegalAccessException e) { e.printStackTrace(); } return result; } }
package test.jdbc; import com.jdbc.ReflectionUtils; import com.jdbc.User; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.InputStream; import java.sql.*; import java.util.*; public class JDBCResultObject { private Connection conn; private ResultSet resultSet; @BeforeEach public void start() throws Exception { Properties properties = new Properties(); InputStream in = this.getClass().getClassLoader().getResourceAsStream("jdbc.properties"); properties.load(in); String driver = properties.getProperty("driver"); String jdbcUrl = properties.getProperty("jdbcUrl"); String user = properties.getProperty("user"); String password = properties.getProperty("password"); Class.forName(driver); conn = DriverManager.getConnection(jdbcUrl, user, password); } @AfterEach public void end() throws Exception { if (resultSet != null) { resultSet.close(); } if (conn != null) { conn.close(); } } @Test public void testResultSetOfObject() { ResultSetMetaData(User.class, "SELECT * FROM user where id > ?", 0); } public <T> void ResultSetMetaData(T t, String sql, Object... args) { try { PreparedStatement preparedStatement = conn.prepareStatement(sql); for (int i = 0; i < args.length; i++) { preparedStatement.setObject(i + 1, args[i]); } resultSet = preparedStatement.executeQuery(); // 得到 ResultSetMetaData 对象 ResultSetMetaData rsmd = resultSet.getMetaData(); // 封装结果集 List<Map<String, Object>> resultList = new ArrayList<>(100); Map<String, Object> values = null; while (resultSet.next()) { values = new HashMap<>(20); for (int i = 0; i < rsmd.getColumnCount(); i++) { String columnLabel = rsmd.getColumnLabel(i + 1); Object columnValue = resultSet.getObject(columnLabel); values.put(columnLabel, columnValue); } resultList.add(values); } List<T> list = new ArrayList<>(100); T object = null; // 结果集转为对象 for (Map<String, Object> objectMap : resultList) { object = (T) ((Class) t).newInstance(); for (Map.Entry<String, Object> entry : objectMap.entrySet()) { String fieldName = entry.getKey(); Object fieldValue = entry.getValue(); ReflectionUtils.setFieldValue(object, fieldName, fieldValue); } list.add(object); } System.out.println(list); } catch (Exception e) { e.printStackTrace(); } } }
原文:https://www.cnblogs.com/jhxxb/p/10439567.html