使用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);