Jacob Garber
Jacob Garber

Reputation: 364

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:

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?

Upvotes: 5

Views: 1020

Answers (2)

Saltuk
Saltuk

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

Clashsoft
Clashsoft

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

Related Questions