Using Nashorn as an embedded interpreter

A more common use of Nashorn, compared to using it as a command-line tool, is using it as an embedded interpreter. The javax.script API is public and can be accessed via the nashorn identifier. The following code demonstrates how we can gain access to Nashorn, define a JavaScript function, and obtain the results--all from within a Java application:

    // required imports    import javax.script.ScriptEngine;    import javax.script.ScriptEngineManager;    public class EmbeddedAddTest     {      public static void main(String[] args) throws Throwable      {        // instantiate a new ScriptEngineManager        ScriptEngineManager myEngineManager =          new ScriptEngineManager();        // instantiate a new Nashorn ScriptEngine        ScriptEngine myEngine ...

Get Java 9: Building Robust Modular Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.