文章来源:csdn 龙四哥 ticmy
需要导入的包
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
第一种方式
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("javascript");
String exp = "a+b";
scriptEngine.put("a", 4);
scriptEngine.put("b", 15);
Object result = scriptEngine.eval(exp);
System.out.println(exp + "=" + result);
第二种方式ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("javascript");
String exp = "2*6-(6+5)";
Object result = scriptEngine.eval(exp);
System.out.println(exp + "=" + result);