首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

struts中透过反射给领域对象赋值的方法

2012-10-28 
struts中通过反射给领域对象赋值的方法在struts的action中 总有这样的情况用struts1.x是从from里取值 然后

struts中通过反射给领域对象赋值的方法
在struts的action中 总有这样的情况
用struts1.x是从from里取值 然后放入一个对象
用struts2.x是从this.里取值 然后放入一个对象
然后对这个对象进行操作

代码一大串都出现在action中
非常难看 代码质量下降 总是在拷贝粘贴代码
刚写了个类解决这个问题

package com.harmony.themis.onDuty.web.action;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.HashMap;import java.util.Map;import com.harmony.themis.commons.web.action.BaseAction; public class ObjectSetValue  { public Object getValueByAction(String returnClassName/*需要赋值的类的className*/, BaseAction baseAction/*你的action父类是谁这里就写谁 如果是自定义的这个参数类型得改 也可以是from*/)  {Object obj =  null;Map map = new HashMap();Method[] methodes = null;//将action中所有方法放入到map 中 这个map只为查询是否有get方法methodes = baseAction.getClass().getMethods();for(Method met : methodes){ map.put(met.getName(), "");}try {  obj = Class.forName(returnClassName).newInstance();} catch (InstantiationException e) { e.printStackTrace();} catch (IllegalAccessException e) { e.printStackTrace();} catch (ClassNotFoundException e) { e.printStackTrace();}try {methodes = Class.forName(returnClassName).getMethods();} catch (SecurityException e) { e.printStackTrace();} catch (ClassNotFoundException e) { e.printStackTrace();}//循环类的所有方法for(Method met : methodes){ //如果是set方法if(met.getName().indexOf("set")==0){//得到除去set的属性名String metName = met.getName().replaceFirst("set", "");//得到get方法的方法名String getMetName = "get"+metName;try {//如果action中有对应的get方法if(map.containsKey(getMetName)){  //执行类的set方法 对应action的get方法 met.invoke(obj,new Object[] {baseAction.getClass().getMethod(getMetName,   new  Class[]{ }).invoke(baseAction, new  Class[]{ }) } ) ; }} catch (IllegalArgumentException e) {e .printStackTrace();} catch (IllegalAccessException e) {e .printStackTrace();} catch (InvocationTargetException e) {e .printStackTrace();} catch (SecurityException e1) {e1.printStackTrace();} catch (NoSuchMethodException e1) {    e1.printStackTrace();}}}return obj;}}
1 楼 congdepeng 2010-04-21   观望本贴 2 楼 weiqingfei 2010-04-21   Apache的commons-beanutils包里,有个叫做BeanUtils.copyProperties的方法。 3 楼 gulufather 2010-04-21   weiqingfei 写道Apache的commons-beanutils包里,有个叫做BeanUtils.copyProperties的方法。
多谢提醒 还是我孤陋寡闻了 一会去看看 4 楼 nothink 2010-04-27   有样东西叫OGNL

热点排行