题主可以看一下是不是要这种效果:
假设有两个表达式ruleStr1 ,ruleStr2,给定不同的num,通过一个方法判断表达式是否成立
String ruleStr1 ="num>70 && num<90"; // 满足规则返回true
String ruleStr2 ="num>=70 || num<90"; // 不满足规则返回false
以下代码我是按照这个理解来实现的,你可以看看是否是你想要的效果
import java.util.HashMap;
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 Test {
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);
}
public static Boolean getResult(int num, String ruleStr){
Map<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
String expression = ruleStr;
Object code = convertToCode(expression, map);
return Boolean.valueOf(code.toString());
}
public static void main(String[] args) {
String ruleStr1 ="num>70 && num<90"; // 满足规则返回true
String ruleStr2 ="num>=70 || num<90"; // 不满足规则返回false
System.out.println(getResult(80,ruleStr1));
System.out.println(getResult(90,ruleStr1));
System.out.println(getResult(80,ruleStr2));
System.out.println(getResult(100,ruleStr2));
}
}