Monday, April 7, 2014

nashorn JavaScript exercise, call JavaScript function from Java

Example to call function and get result in Javascript, from Java code:

JavaTestNashornJavascript.java
package javatestnashornjavascript;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaTestNashornJavascript {
    
    final String myJavascript = "<path to myjavascript.js>";
    
    JavaTestNashornJavascript(){
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");

        try {
            FileReader fileReader = new FileReader(myJavascript);
            nashorn.eval(fileReader);

            Invocable invocable = (Invocable) nashorn;

            Object jsResult = invocable.invokeFunction(
                    "javascriptFunction", "Java-Buddy");
            System.out.println("result returned to Java from JavaScript: " + jsResult);

        } catch (FileNotFoundException 
                | ScriptException 
                | NoSuchMethodException ex) {
            Logger.getLogger(JavaTestNashornJavascript
                    .class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String[] args) throws URISyntaxException {
        
        JavaTestNashornJavascript javaTestNashornJavascript = 
                new JavaTestNashornJavascript();

    }

}


myjavascript.js
var javascriptFunction = function(para){
    print("para passed from Java to JavaScript: " + para);
    return "Hello " + para;
}



more nashorn JavaScript exercise:


No comments:

Post a Comment