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 = myEngineManager.
getEngineByName("nashorn");

// create the JavaScript function
myEngine.eval("function addTest(x, y)
{ return x + y; }");

// generate output including a call to the
// addTest function via the engine
System.out.println("The addition results are:
" + myEngine.eval("addTest(300, 19);"));
}
}

Here is the output that's provided in the console window:

Console output

This is a simplistic example to give you an idea of what is possible with the embedded use of Nashorn. There are ample examples in Oracle's official documentation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset