I have a Java program that generates a mathematical equation based on user input. I'd like to evaluate the equation, but iterating over its syntax tree is rather slow. A faster solution is to put the equation in a Java file, compile it, and call the compiled code (during runtime). Here is what I am currently doing:
Create an Equation.java
file with the function as a static member. For example, if the equation generated is 3*x + 2*y
(the real equation is much more complicated), the program would create the file
public class Equation {
public static DoubleBinaryOperator equation = (x, y) -> 3*x + 2*y;
}
Equation.class
using JavaCompiler
This is an enormous amount of boilerplate for something that seems like it should be simple. Is there an easier way of turning this equation into a function and calling it at runtime?
Depending on how complex your equation is, the JavaScript evaluation engine Nashorn
might be worth a try.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With