1.业务背景
有一个业务表,数值点字段较多(好在命名差别只在编号上,才能方便使用动态加载),在实体类赋值时,如果一个一个字段赋值,写成obj.setDataValue1;2;3…这样的话,会占用太多行并且显得很low,不优雅。
2.解决方案
找了一下相关帖子,看了几个,内容大同小异,互相搬运吧。试了一下,好用,这里记录一下要点,以防原帖消失(参考的原帖地址:https://www.jb51.net/article/143964.htm)。
工具包:commons-jexl
maven依赖(取自https://mvnrepository.com/):
org.apache.commons commons-jexl 2.1.1
3.主要代码
添加一个动态加载方法的工具类(通用,可直接搬运):
public class MethodUtil {
public static Object invokeMethod(String jexlExp, Map map){
JexlEngine jexl=new JexlEngine();
expression e = jexl.createexpression(jexlExp);
JexlContext jc = new MapContext();
for(String key:map.keySet()){
jc.set(key, map.get(key));
}
if(null==e.evaluate(jc)){
return "";
}
return e.evaluate(jc);
}
}
使用示例:
Mapmap=new HashMap (2);//不确定有几个key就写16。 map.put("testService",testService); map.put("person",person); String expression="testService.save(person)"; DyMethodUtil.invokeMethod(expression,map);
要点:需要被解析的对象实例与被处理的数据体,要放在这个map中,方法名(比如setxxx)不必放在map。
这样就可以通过循环写出多个obj.setDataValuexxxxxx(valueItem)了,总体是节省不少代码量的。



