Tuesday, April 8, 2014

nashorn JavaScript exercise, call Java method from JavaScript

This example show how to call Java javaStaticMethod() in "javatestnashornjavascript.JavaTestNashornJavascript" class.

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 String javaStaticMethod(String para){
        System.out.println("javaStaticMethod("+para+") called");
        String rev = new StringBuilder(para).reverse().toString();
        return rev;
    };

    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);
    
    var myClass = Java.type("javatestnashornjavascript.JavaTestNashornJavascript");
    var revPara = myClass.javaStaticMethod(para);
    
    return "Hello " + revPara;
};



No comments:

Post a Comment