服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

定制一个灵活的struts框架

用过struts的朋友应该都知道,struts的action类提供的execute方法有四个参数,这是一种非常大范围的解决方案,而现实中我们的action类中的方法可能只处理或者只需要个别参数,也许只需要actionform,或者甚至你都不需要,下面的代码为大家展示如何通过java的反射机制来灵活实现.
-------------
      /*  all code should insert into excute method of actionclass*/
     
      /*  get the type of the current actionclass*/
      class clazz = this.getclass(  );
     
     
      /*      get all the methods in this actionclass       */
      method[] methods = clazz.getmethods;
     
      /*      put all the method into hashmap               */
      hashmap methodss = new hashmap(  );
      for(int i=0;i<methods.length;i++){
      methodss.add(methods[i].getname(),methods[i])
      }
     
      /*      get the name of the method you want invokde  */
      string methodsname=request.getparameter("methodsname");
     
     
      /*      choose the method that you want invoke      */
      class[] para= methodss.get("methodsname").getparametertypes();
      try {
  if (para.length==1){
     if (para[0].getclass().newinstance() instanceof  actionform) {
      
    object[] argst ={form};
    return (actionforward) method.invoke( this,  argst);
    
   }
    .................................. 
     
    }
 } catch (instantiationexception e) {
   todo auto-generated catch block
  e.printstacktrace();
 }


-----------

这样,开发人员就可以在action中按自己的需要来写方法了,为将来单体的测试也很有用,毕竟四个参数全用的情况是很少的,当然,我现在写的还有问题,就是方法的名称不能重复,这是因为目前处理的地方不是很好,希望大家一起讨论........

扫描关注微信公众号