要评估String中的数学表达式,请使用Java中的Nashorn JavaScript(即脚本)。Nashorn调用Java 7中引入的动态功能以提高性能。
要编写脚本,请对引擎使用ScriptEngineManager类-
ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
现在,对于来自字符串的JavaScript代码,请使用eval即执行脚本。在这里,我们正在评估字符串中的数学表达式-
Object ob = scriptEngine.eval("9 + 15 + 30"); System.out.println("Result of evaluating mathematical expressions in String = "+ob);
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; public class Main { public static void main(String[] args) throws Exception { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript"); //来自String的JavaScript代码 Object ob = scriptEngine.eval("9 + 15 + 30"); System.out.println("Result of evaluating mathematical expressions in String = "+ob); } }
输出结果
Result of evaluating mathematical expressions in String = 54