使用commons的jexl可实现将字符串变成可执行代码的功能
例子(来源:http://wiselyman.iteye.com/blog/1677444)
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;
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);