Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create and compile a function in Java 8

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;
    }
    
  • Compile it into Equation.class using JavaCompiler
  • Dynamically import the class file and call the equation using reflection

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?

like image 953
Mr Bingley Avatar asked Nov 09 '22 08:11

Mr Bingley


1 Answers

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
like image 128
Clashsoft Avatar answered Nov 14 '22 21:11

Clashsoft