With the JavaScript API over Rhino you can simply compile the script using the Compilable
interface. For example:
public class CompileScript {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = engineManager.getEngineByName("js");
//cast to Compilable engine, this is safe for Rhino
Compilable c = (Compilable) scriptEngine;
CompiledScript script = c.compile("print('Hello World')"); //compile
script.eval();
}
}
However the benefits of this will show up when running several times the script. Basically it reduces the overhead of re-interpret every time. From the CompiledScript
javadoc:
Extended by classes that store results of compilations. State might be stored in the form of Java classes, Java class files or scripting language opcodes. The script may be executed repeatedly without reparsing.
Anyway I think you should take a look at the Rhino JavaScript Compiler. It "translates JavaScript source into Java class files".
And there is a V8 Java implementation. Check jav8.