Wednesday, February 22, 2017

How to Embed JavaScript in Java

Java 8 came with a JavaScript engine called Nashorn. This makes it easy to call some JavaScript code from Java. In this example, I'm going to show how to pass some Java object into JavaScript and vice-versa as well as calling creating a Java object from JavaScript.
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleBindings;
import java.util.Map;

public class JsExample {
    public static class JavaClass {
        public String greet() {
            return "Hello from Java";
        }
    }

    public static void main(String[] args) throws Exception {
        final String script =
            "var File = Java.type(\"java.io.File\");" +
            "print(new File(\".\").exists());" +
            "var map = {\"msg\": \"Hello from JS\"};" +
            "print(javaClass.greet());" +
            "map;";

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        Bindings bindings = new SimpleBindings();
        bindings.put("javaClass", new JavaClass());

        Map<String, String> retVal = (Map<String, String>) engine.eval(script, bindings);
        System.out.println(retVal.get("msg"));
    }
}
Output:
true
Hello from Java
Hello from JS

1 comment:

  1. Hi fredyw good job with jsrt A small SRT parser and editor in Java. My blog https://isjavado.wordpress.com/ I have an idea can I talk about?

    ReplyDelete