This blogs talks about how to compile JavaScript from Java
Requirement:
1) Java SE 5
2) jsr223-1.0.jar (http://jcp.org/en/jsr/detail?id=223)
3) js-14.jar (http://www.mozilla.org/rhino/)
4) js.jar (http://www.mozilla.org/rhino/)
Note if you are using Java SE 6 then none of the above jar are needed as it is part of jdk.
Writing a test class:
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/**
*
* @author milind
*/
public class JavaScriptCompileTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension("js");
if (engine instanceof Compilable) {
Compilable compEngine = (Compilable) engine;
try {
CompiledScript script = compEngine.compile("function count(){ var count; function myName() { document};");
} catch (ScriptException e) {
System.out.println("Message : " + e.getCause().getMessage() );
}
} else {
System.err.println("Engine can't compile code the code Scripting Engine Missing");
}
}
}
It will print following on console:
Message : missing } after function body along with stack trace.