08 September, 2013

Run JavaScript from Native Java

I wrote in previous post Execute Javascript code from Java Code how to execute java script in Oracle ADF.
But in this post I will explain how to call Javascript from native Java.



The following code snippets will illustrate how to evaluate Javascript code and invoke functions and get return value.

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class CallJavaScript {
    public static void callJsCode(String jsCode) throws ScriptException,
                                                        NoSuchMethodException {

        // Retrieving the Javascript engine
        ScriptEngine se =
            new ScriptEngineManager().getEngineByName("javascript");
        try {
            se.eval(jsCode);
        } catch (ScriptException e) {
            e.printStackTrace();
        }

        try {
            Invocable jsinvoke = (Invocable)se;
            System.out.println("myFunction(2) returns: " +
                               jsinvoke.invokeFunction("myFunction", 2, 4));
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

    }
}

Then You can call this code using for example
       try {
            String jsCode =
                "function myFunction(x,y){return x+y;}";
            CallJavaScript.callJsCode(jsCode);
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }      

The output of previous code will be

myFunction(2) returns: 6.0

Thanks
Recommended Post Slide Out For Blogger