/**
*
* @author: Longjun
* @Description: 使用commons的jexl可实现将字符串变成可执行代码的功能
* @date:2016年3月21日 下午1:45:13
*/
public static Object convertToCode(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);
}
示例1
public static void main(String[] args) {
try {
Map<String,Object> map=new HashMap<String,Object>();
map.put("money",2100);
String expression="money>=2000&&money<=4000";
Object code = convertToCode(expression,map);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
示例2
public static void main(String[] args) {
try {
Map<String,Object> map=new HashMap<String,Object>();
map.put("testService",testService);
map.put("person",person);
String expression="testService.save(person)";
convertToCode(expression,map);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
jar
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-jexl</artifactId>
<version>2.0</version>
</dependency>