Reputation: 364
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 JavaCompilerThis 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?
Upvotes: 5
Views: 1020
Reputation: 1159
why you have to compile it on runtime .. compile as it jar .. and save it to a folder .. load it on runtime ..
here is an usefull answer how to load jar file
How to load a jar file at runtime
Upvotes: 0
Reputation: 11882
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
Upvotes: 1