Java jdbc封装 反向映射之查询

来源:互联网 发布:淘宝联盟能赚钱吗 编辑:程序博客网 时间:2024/06/08 15:17

1.获取set方法

//获取set方法public Method getSetName(String name,Object obj) throws Exception, SecurityException {Field[] fields = obj.getClass().getDeclaredFields();Method method = null;for (int i = 0; i < fields.length; i++) {if( fields[i].getName().equals(name)){StringBuffer sb = new StringBuffer("set");sb.append(name.toUpperCase().charAt(0));sb.append(name.substring(1));method= obj.getClass().getMethod(sb.toString(), fields[i].getType());}}return method;}

2.调用set方法

// 执行set方法public Object getSetMethod(Object obj,Method m, Object object) throws Exception {m.invoke(obj, object);return obj;}

3.查询方法

//查找public List<Object> getListInfo(String sql, Object[] object,List list,Object obj)throws Exception{List<Object> listobj = new ArrayList();conn = this.getConnection();ps = conn.prepareStatement(sql);if (object != null) {for (int i = 0; i < object.length; i++) {logger.info(object[i]);ps.setObject(i + 1, object[i]);}}rs=ps.executeQuery();while(rs.next()){Object o=oh.newObject(obj);for(int i=0;i<list.size();i++){Method m=oh.getSetName(list.get(i).toString(), o);o=oh.getSetMethod(o, m, rs.getObject(list.get(i).toString()));}listobj.add(o);}return listobj;}

补充如何新建object对象

//新建反射对象public Object newObject(Object obj) throws ClassNotFoundException{ Object object = null;try {object = obj .getClass().newInstance();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}return object;}
4.增删查请看


Java jdbc封装 反向映射之查询

5.学习之路,道阻且长,行则将至