我有一个Java程序,它根据用户输入生成一个数学方程式.我想评估这个等式,但迭代它的语法树是相当慢的.更快的解决方案是将等式放入Java文件,编译它,并调用已编译的代码(在运行时).这是我目前正在做的事情:
Equation.java使用该函数创建一个文件作为静态成员.例如,如果生成的等式是3*x + 2*y(实际等式更复杂),程序将创建文件
public class Equation {
public static DoubleBinaryOperator equation = (x, y) -> 3*x + 2*y;
}
Run Code Online (Sandbox Code Playgroud)Equation.class使用JavaCompiler将其编译对于看起来应该简单的东西来说,这是一个巨大的样板.是否有更简单的方法将此等式转换为函数并在运行时调用它?
根据您的方程的复杂程度,JavaScript 评估引擎Nashorn可能值得一试。
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
Object o = engine.eval("1 + 2 * 3");
System.out.println(o); // prints 7
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("x", 10);
System.out.println(engine.eval("x + 1")); // prints 11
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
658 次 |
| 最近记录: |