Executing JavaScript on a Java VM

These days I stumbled upon an interesting feature of the Java Virtual Machine. Since version 1.6 you can request from your Java code a ScriptEngineManager. This factory allows you to request an execution engine for JavaScript, which can be used to execute arbitrary JavaScript code within your Java program.

The following snippet demonstrates how to execute a string containing JavaScript code:

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
if (engine != null) {
  try {
    engine.eval(script);
  } catch (ScriptException e) {
    throw new JsExecutionException(e);
  }
} else {
  throw new JsExecutionException("No JavaScript engine available.");
}

To try this JVM feature out, I implemented a small java application that executes a JavaScript given as command line parameter. You can find the sources on github: https://github.com/siom79/js-executor.git.

Tags: , ,

Leave a comment

Design a site like this with WordPress.com
Get started