三如何应用类反射机制简化Struts应用程序的开发: 先定义Action FormBean: package combhskywebissystem; import orgapachestrutsaction*; import javaxservlethttp*; public class UsersActionForm extends ActionForm { private String usr_id; private String usr_name; public void setUsr_id(String usr_id) { thisusr_id = usr_id; } public String getUsr_id() { return usr_id; } public String getUsr_memo() { return usr_memo; } public void setUsr_name(String usr_name) { thisusr_name = usr_name; } } 编写通用的为ActionFormBean赋值的方法 ///////////////////////////////////////////////////////////////////////////// //Function: 完成ResultSet对象向ArrayList对象为集合的对象的转化 //Para:sql指定的查询Sql //Para:classNameSql相对应得JavaBean/FormBean类的名字 //Return:以类className为一条记录的结果集完成ResultSet对象向ArrayList对象为集 //合的className对象的转化 ////////////////////////////////////////////////////////////////////////////// public ArrayList Select(String sqlString className){ ArrayList paraList=new ArrayList(); try{ if (conn == null){ Connection(); } PreparedStatement stmt = connprepareStatement(sql); ResultSet rs = stmtexecuteQuery(); String recordValue=; Object c=null; paraList=new ArrayList(); ResultSetMetaData rsmd = rsgetMetaData(); int columnCount = rsmdgetColumnCount(); while (rsnext()){ c=ClassforName(className)newInstance(); for (int i=; i<=columnCount; i++) { if(rs.getString(rsmd.getColumnName(i))!=null){ recordValue=rs.getString(rsmd.getColumnName(i)); }else{ recordValue=""; } Method m=c1.getClass().getMethod(getSetMethodName(rsmd.getColumnName(i)), new Class[]{recordValue.getClass()}); m.invoke (c1, new Object[]{recordValue}); } paraList.add(c1); } }catch(SQLException ex){ }catch(ClassNotFoundException e){ }catch(NoSuchMethodException e) { }catch(InvocationTargetException e){ }catch (IllegalAccessException e){ }catch(InstantiationException e){ } finaly{ closeConnection(); return paraList; } } 3、 在JavaBean封装的商业逻辑中调用Select 方法,然后在JSP页面上显示出来: //Function:取得用户列表 //Para: //Return:返回用户列表 ///////////////////////////////////////////////////////////////////////////// public ArrayList getUsers(){ ArrayList ret=null; DatabaseManage db=new DatabaseManage(); String sql=" select usr_id,usr_name " +" from users " ; ret=db.Select(sql," com.bhsky. webis.system.UsersActionForm"); return ret; } 4、 在Action的execute方法中调用getUsers()方法: public ActionForward execute( ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse httpServletResponse) { /**@todo: complete the business logic here, this is just a skeleton.*/ UsersActionForm uaf=(UsersActionForm)actionForm; SystemService ubb=new SystemService(); ArrayList userList=ubb.getUsers(); request.setAttribute("userList",userList); ActionForward actionForward=actionMapping.findForward(url); return actionForward; } 5、 在JSP中显示: 用户ID 姓名 四、结语: 我们通过运用类反射机制,在一个Struts应用开发中,完成了一个通用查询方法的实现。tw.WIngWit.cOm它使得程序员摆脱了在每个应用程序中都要编写枯燥的set、get等方法来访问ActionForm Bean,从而简化了Struts应用程序的开发。