三、如何应用类反射机制简化Struts应用程序的开发: 1、 先定义Action FormBean: package com.bhsky.webis.system; import org.apache.struts.action.*; import Javax.servlet.http.*; public class UsersActionForm extends ActionForm { private String usr_id; private String usr_name; public void setUsr_id(String usr_id) { this.usr_id = usr_id; } public String getUsr_id() { return usr_id; } public String getUsr_memo() { return usr_memo; } public void setUsr_name(String usr_name) { this.usr_name = usr_name; } } 2、 编写通用的为ActionFormBean赋值的方法: ///////////////////////////////////////////////////////////////////////////// //Function: 完成ResultSet对象向ArrayList对象为集合的对象的转化 //Para:sql,指定的查询Sql //Para:className,Sql相对应得JavaBean/FormBean类的名字 //Return:以类className为一条记录的结果集,完成ResultSet对象向ArrayList对象为集 //合的className对象的转化 ////////////////////////////////////////////////////////////////////////////// public ArrayList Select(String sql,String className){ ArrayList paraList=new ArrayList(); try{ if (conn == null){ Connection(); } PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); String recordValue=""; Object c1=null; paraList=new ArrayList(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); while (rs.next()){ c1=Class.forName(className).newInstance(); for (int i=1; 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页面上显示出来: