// 在此输入java代码 * @[author]param[/author] args */ public static void main(String[] args) { String sql="select * from user where name=1"; try { User user=BaseDao.getClass(sql, User.class); System.out.println(user.getName()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 使用泛型类封装查询结果 * @[author]param[/author] <T> * @throws Exception */ public static <T> T getClass(String sql, Class<T> clazz) throws Exception { PreparedStatement ps = null; ResultSet rs = null; Connection con=JDBCUtil.getConnection(); ps=con.prepareStatement(sql); rs=ps.executeQuery(); //结果集的字段 ResultSetMetaData md=rs.getMetaData(); //将字段添加到string数组 String[] mdString=new String[md.getColumnCount()]; for(int i=0;i<md.getColumnCount();i++) { mdString[i]=md.getColumnLabel(i+1); } //声明一个泛型类 T t=null; //获得传入类的方法集合 Method[] methods=clazz.getMethods(); if(rs.next()) { t=clazz.newInstance(); for(int j=0;j<mdString.length;j++) { String clsMethod=mdString[j]; //将结果集的字段首字母替换成大写并且以set开头(例:setName对象类里面的set方法) clsMethod="set"+clsMethod.replaceFirst(clsMethod.substring(0,1), clsMethod.substring(0, 1).toUpperCase()); for(Method m:methods) { //匹配传入类的方法集合如果匹配成功则执行。 if(clsMethod.equals(m.getName())) { m.invoke(t, rs.getObject(j+1)); } } } } return t; }
|