1、JexlEngine计算表达式
/** * @author chuan * @title: JexlEngineTest * @description: TODO(JexlEngine表达式判断) */ public class JexlEngineTest { 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 void main(String[] args) { try { Map<String, Object> map = new HashMap<String, Object>(); map.put("count", 5100); String expression = "count>=1000&&count<3000"; Object code = convertToCode(expression, map); System.out.println("execute result: " + code); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
输出结果:
2、ScriptEngine执行JS脚本
public static void main(String[] args) throws Exception { ScriptEngine engine = new ScriptEngineManager().getEngineByName("js"); Compilable compilable = (Compilable) engine; Bindings bindings = engine.createBindings(); String script = "function add(op1,op2){return op1+op2;} add(param1, param2)"; // 定义函数并调用 CompiledScript JSFunction = compilable.compile(script); // 解析编译脚本函数 // 通过Bindings加入参数 bindings.put("param1", 10); bindings.put("param2", 20); // 调用缓存着的脚本函数对象,Bindings作为参数容器传入 Object result = JSFunction.eval(bindings); System.out.println("execute result: " + result); }
执行结果: