Dynamically create and compile a function in Java 8

I have a Java program that generates a mathematical equation based on user input. I would like to evaluate the equation, but the iteration over its syntax tree is rather slow. A faster solution is to install the equation in a Java file, compile it, and call the compiled code (at run time). Here is what I am doing now:

  • Create an Equation.java file with the function as a static member. For example, if the generated equation is 3*x + 2*y (the real equation is much more complicated), the program will create a file

     public class Equation { public static DoubleBinaryOperator equation = (x, y) -> 3*x + 2*y; } 
  • Compile it in Equation.class using JavaCompiler
  • Dynamically import a class file and invoke an equation using reflection

This is a huge number of templates for something similar, which should be simple. Is there an easier way to turn this equation into a function and call it at run time?

+5
source share
2 answers

Depending on how complex your equation is, it might be worth a try out Nashorn JavaScript score engine.

 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 
+1
source

why you should compile it at runtime. Compile it as a jar .. and save it in a folder .. Download it at run time.

here is a useful answer how to download jar file

How to load jar file at runtime

0
source

All Articles