Thursday, 18 April 2013

Calling Javascript From Java (Example)

This post explains how to call Javascript from Java. The code example is available at GitHub in the Java-Javascript-Calling directory.

Code Example

We create some small Javascript code in a string. This code dumps "Hello World!" and defines a function called myFunction() adding 3 to the provided value:
public class JavascriptCalling {

    public static final String MY_JS
        = "print(\"Hello world!\\n\");"
        + "var myFunction = function(x) { return x+3; };";

    public static void main(String[] args)
            throws ScriptException, NoSuchMethodException {

        // Retrieving the Javascript engine
        ScriptEngine se = new ScriptEngineManager()
            .getEngineByName("javascript");

        if ( Compilable.class.isAssignableFrom(se.getClass()) ) {

            // We can compile our JS code
            Compilable c = (Compilable) se;
            CompiledScript cs = c.compile(MY_JS);

            System.out.println("From compiled JS:");
            cs.eval();

        } else {

            // We can't compile our JS code
            System.out.println("From interpreted JS:");
            se.eval(MY_JS);

        }

        // Can we invoke myFunction()?
        if ( Invocable.class.isAssignableFrom(se.getClass()) ) {

            Invocable i = (Invocable) se;
            System.out.println("myFunction(2) returns: "
                + i.invokeFunction("myFunction", 2));

        } else {

            System.out.println(
                "Method invocation not supported!");

        }

    }

}
The above starts by retrieving the Javascript engine. Next, if one can compile the Javascript, our code is compiled. The script is executed, which prints "Hello World!". Last, if the engine allows invocation, we call our function defined in our Javascript code.

The result is: