1 package luowuhui.utils; 2 3 import java.lang.reflect.Field; 4 import java.lang.reflect.Method; 5 import java.sql.ResultSet; 6 import java.util.ArrayList; 7 import java.util.List; 8 9 public class CreateBean { 10 11 /** 12 * @return 13 * @see 返回单个实体对象 14 */ 15 public static <T> T getBean(Class<T> calss, ResultSet resultSet) { 16 // TODO Auto-generated method stub 17 // 创建对象 18 T object = null; 19 try { 20 object = createBean(calss, resultSet); 21 22 } catch (Exception e) { 23 System.out.println("执行CreateBeanImp类getBean方法出现异常"); 24 System.out.println("=================异常报告================="); 25 e.printStackTrace(); 26 System.out.println("=================end================="); 27 } 28 29 return object; 30 } 31 32 /** 33 * @see 返回实体对象集 34 */ 35 public static <T> List<T> getBeans(Class<T> calss, ResultSet resultSet) { 36 List<T> ts = null; 37 try { 38 ts = new ArrayList<>(); 39 int i = 0; 40 while (resultSet.next()) { 41 System.out.println(++i); 42 ts.add(createBean(calss, resultSet)); 43 } 44 } catch (Exception e) { 45 System.out.println("执行CreateBeanImp类getBean方法出现异常"); 46 System.out.println("=================异常报告================="); 47 e.printStackTrace(); 48 System.out.println("=================end================="); 49 } 50 return ts; 51 } 52 53 /** 54 * @说明 创建实体 55 * @param calss 56 * @param resultSet 57 * @return 实体对象 58 * @throws Exception 59 * <p> 60 * 创建对象时错误,69行<br> 61 * 获取resultSet值错误81行 62 * </p> 63 */ 64 private static <T> T createBean(Class<T> calss, ResultSet resultSet) throws Exception { 65 T object = calss.newInstance(); 66 // 获取字段 67 Field[] fields = calss.getDeclaredFields(); 68 69 // 遍历fields 70 for (Field field : fields) { 71 // 获取字段名 72 String fieldName = field.getName(); 73 if (!fieldName.equalsIgnoreCase("serialVersionUID")) { 74 // 获取方法名 75 String setMethodName = "set" + (char) (fieldName.charAt(0) - 32) + fieldName.substring(1); 76 // 获取field类型 77 Class type = field.getType(); 78 79 Method method = calss.getDeclaredMethod(setMethodName, type); 80 Object fieldVlaue = resultSet.getObject(fieldName); 81 // System.out.println(setMethodName + ":" + fieldVlaue); 82 method.invoke(object, fieldVlaue); 83 } 84 85 } 86 // System.out.println(); 87 // System.out.println(object); 88 return object; 89 } 90 }