package cn.huizhi.user.tool; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; /** * jdbc封装类 * clazz : bean类型 * result :结果集 * arrayList : 用于包装bean类型的数据 * 实现思路 * 1: 使用反射获取所有成员变量:getDeclaredFields * 2: 以变量名跟字段相同的情况获取result的值 * 3: 以javabean规则set+大写+变量名,赋值 * 4:防止方法为private修饰,故加setAccessible(true)取消安全检查 */ @SuppressWarnings({ "unchecked", "rawtypes" }) public class ClassReflectionTool { public static void findAll(Class clazz, ResultSet result,List arrayList) { try { Field[] fields = clazz.getDeclaredFields(); while(result.next()){ Object newInstance = clazz.newInstance(); for (Field f : fields) { String fieldName = f.getName(); Class fieldClass = (Class) f.getGenericType(); String objVal = (String) result.getObject(fieldName); Method method = clazz.getMethod(change(fieldName),fieldClass); method.setAccessible(true);//取消检查 method.invoke(newInstance, objVal); //System.out.println("字段名:" + f.getName() + "\t 类型为" + fieldType); } arrayList.add(newInstance); } } catch (IllegalAccessException e) { throw new RuntimeException("初始化..."+clazz+"...失败"); } catch (InstantiationException e) { throw new RuntimeException("初始化..."+clazz+"...失败"); } catch (SQLException e) { throw new RuntimeException("字段 与 "+clazz+"中有变量名不匹配"+e); } catch (SecurityException e) { throw new RuntimeException("找不到set方法\t"+e); } catch (Exception e) { e.printStackTrace(); } } private static String change(String fieldName) { StringBuilder sb = new StringBuilder("set"); sb.append(fieldName.substring(0, 1).toUpperCase()); sb.append(fieldName.substring(1,fieldName.length())); return sb.toString(); } }
原文:http://blog.csdn.net/hubiao_0618/article/details/19616507