用過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中按自己的需要來寫方法了,為將來單體的測試也很有用,究竟四個參數全用的情況是很少的,當然,我現在寫的還有問題,就是方法的名稱不能重復,這是因為目前處理的地方不是很好,希望大家一起討論........
新聞熱點
疑難解答