Apache Commons JEXL实现字符串转换成可执行代码
2018-03-21 14:34:38
956次阅读
0个评论
使用Apache Commons 的JEXL可实现将字符串变成可执行代码的功能,
封装功能类:
import java.util.Map;
import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.MapContext;
/**
* 动态加载方法
* @author wangyfc
*
*/
public class DyMethodUtil {
public static Object invokeMethod(String jexlExp,Map<String,Object> 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);
}
}
调用方式:
Map<String,Object> map=new HashMap<String,Object>();
map.put("testService",testService);
map.put("person",person);
String expression="testService.save(person)";
DyMethodUtil.invokeMethod(expression,map);
00