Java 6 – JavaScript Support

One of the new features in Java 6 is the ability to execute code written in scripting languages such as JavaScript. Java 6 will be released with the Mozilla Rhino engine for JavaScript.

Let me get straight to an example:

Lets look at the method runInlineJSCode.

  • First we import the required classes from the new package javax.script.
  • ScriptEngineManager is our entry point into the scripting module.
  • We use an instance of the ScriptEngineManager to get to a script engine represented by ScriptEngine. This can be done by specifying the language name. There are other ways to get to the ScriptEngine. I will only use this one.
  • After that you are free to do pretty much anything you want(as supported by the scripting engine of choice). For example we call the method jsEngine.eval to execute arbitrary lines of code against the scripting engine. In this case the Rhino JavaScript engine.
  • If you execute the above code you will see ‘Hello from inline exec!’printed out on the console.

Next we look at a slightly different scenario. We have an external JavaScript file and we want to execute some code in that file.Refer to method runInlineJSCode.

  • First we import the required classes from the new package javax.script.
  • This time we get a reference to a InputStream for the external JavaScript file greetings.js.
  • Also I send in a variable ‘name’ into the jsEngine. In my case the JavaScript modifies the content and you will be able to access the updated value through the engine, The js code is listed below.Really simple there.
  • Now we call the method jsEngine.eval to execute the JavaScript code.
  • If you execute the above code you will see ‘JavaScript says – how do u do Mathew! ‘ printed out on the console.

The JavaScript code in greetings.js

The result of executing the java code is:

This is all well and good. I can see this feature being used constructively but also open to abuse. Here is a good scenario. Often on web applications that require credit card processing there is some code in JavaScript to perform validations on the card numbers. Rather than recode that in Java we could call out to the same JavaScript method to perform the validation.

Here is a bad scenario. Developers (or Architects) decide to integrate multiple scripting languages into the same project (JavaScript, Groovy, Ruby etc). This can be a painful architecture to maintain. I will leave it that.