Java generic class reflection encapsulation result set

From , 5 Years ago, written in Java, viewed 172 times.
URL https://pastebin.vip/view/4a08142c
  1. /**
  2.  * @param args
  3.  */
  4. public static void main(String[] args) {
  5.     String sql="select * from user where name=1";
  6.     try {
  7.         User user=BaseDao.getClass(sql, User.class);
  8.         System.out.println(user.getName());
  9.     } catch (Exception e) {
  10.         // TODO Auto-generated catch block
  11.         e.printStackTrace();
  12.     }
  13.  
  14. }  
  15.        /**
  16.  * 使用泛型类封装查询结果
  17.  * @param <T>
  18.  * @throws Exception
  19.  */
  20. public static <T> T getClass(String sql, Class<T> clazz) throws Exception {
  21.     PreparedStatement ps = null;
  22.     ResultSet rs = null;
  23.     Connection con=JDBCUtil.getConnection();
  24.     ps=con.prepareStatement(sql);
  25.     rs=ps.executeQuery();
  26.     //结果集的字段
  27.     ResultSetMetaData md=rs.getMetaData();
  28.     //将字段添加到string数组
  29.     String[] mdString=new String[md.getColumnCount()];
  30.     for(int i=0;i<md.getColumnCount();i++) {
  31.         mdString[i]=md.getColumnLabel(i+1);
  32.     }
  33.     //声明一个泛型类
  34.     T t=null;
  35.     //获得传入类的方法集合
  36.     Method[] methods=clazz.getMethods();
  37.     if(rs.next()) {
  38.         t=clazz.newInstance();
  39.         for(int j=0;j<mdString.length;j++) {
  40.             String clsMethod=mdString[j];
  41.             //将结果集的字段首字母替换成大写并且以set开头(例:setName对象类里面的set方法)
  42.             clsMethod="set"+clsMethod.replaceFirst(clsMethod.substring(0,1), clsMethod.substring(0, 1).toUpperCase());
  43.             for(Method m:methods) {
  44.                 //匹配传入类的方法集合如果匹配成功则执行。
  45.                 if(clsMethod.equals(m.getName())) {
  46.                     m.invoke(t, rs.getObject(j+1));
  47.                 }
  48.             }
  49.         }
  50.     }
  51.     return t;
  52. }
  53.  
  54. //源代码片段来自云代码http://yuncode.net
  55.                        

Reply to "Java generic class reflection encapsulation result set"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website