JavaScriptUtil { public static Object eval(final String script, final Map<String, Object> params) throws UtilException { ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("javascript"); try { ScriptContext context = new SimpleScriptContext(); if (params != null) { for (Entry<String, Object> entry : params.entrySet()) { context.setAttribute(entry.getKey(), entry.getValue(), ScriptContext.ENGINE_SCOPE); } } return engine.eval(script, context); } catch (ScriptException e) { throw new UtilException(ErrorCodeDef.EVAL_JAVASCRIPT_ERROR_10042, e); } }  static Object eval(final String script, final Map<String, Object> params);  }
@Test public void eval() { String script = "1+1"; Double result = Double.valueOf(CommonUtil.getString(JavaScriptUtil.eval(script, null))); Assert.isTrue(result - 2 == 0, ErrorCodeDef.SYSTEM_ERROR_10001); Bean bean = new Bean("张三", NUM_18); Map<String, Object> params = new HashMap<>(); params.put("b", bean); script = "b.getAge() + 2"; result = Double.valueOf(CommonUtil.getString(JavaScriptUtil.eval(script, params))); Assert.isTrue(result - NUM_20 == 0, ErrorCodeDef.SYSTEM_ERROR_10001); }