以前刚学jdbc每次需要从数据库select数据然后赋值给一个javabean都要写大一段代码,今天用反射实现了一个简单的映射: package jdbc; import java.sql.Connection; import java.util.List; public class JDBCUtil { public static List QueryOrUpdate(Class returnType,String sql,Object... objs){ List list = null; try { Util util = new Util(); Connection connection = null; connection =util.getConnection(); Param param = null; Class[] cla = null; Object[] obj = null; if(objs!=null){ param = new Param(objs); cla = param.getCla(); obj = param.getObjs(); } StatementUtil statementUtil = new StatementUtil(returnType, connection, sql, cla,obj); Pre pre = statementUtil.getPrepareStatement(); ResultSetUtil resultSetUtil = new ResultSetUtil(pre); list = resultSetUtil.getPOJO(); util.release(connection); } catch (Exception e) { e.printStackTrace(); } return list; } } package jdbc; public class Param { private Object[] objs; private Class[] cla; public Param(Object[] objs){ this.objs = objs; cla = new Class[objs.length]; for(int i =0;i getPOJO(){ List list = null; if(!isSelect){ try { preparedStatement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); }finally{ try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } return null; }else{ //select list = new ArrayList(); Object obj =null; ResultSet resultSet = null; try { resultSet = preparedStatement.executeQuery(); Field[] fields = pojo.getDeclaredFields(); while(resultSet.next()){ obj = pojo.newInstance(); Object[] arg = new Object[fields.length]; for(int i=0;i 主要api , JDBCUtil.QueryOrUpdate(Class returnType,String sql,Object... objs) 会自动映射,但是有一些缺陷,比如得到的列名必须和要映射的javabean的属性名相同 StatementUtil这个类可以定制从java属性到数据库的转换,我只在里面添加了int integer double 和string类型的转换,如果有需要可以自己添加 小弟不才,写的不怎么样,有需要完整jar的朋友留个邮箱