Java Reference
In-Depth Information
javax.script , so let's move on to examine that package next, and discuss how Java
interacts with engines for interpreting scripting languages.
Nashorn and javax.script
Nashorn is not the first scripting language to ship with the Java platform. The story
starts with the inclusion of javax.script in Java 6, which provided a general inter‐
face for engines for scripting languages to interoperate with Java.
This general interface included concepts fundamental to scripting languages, such
as execution and compilation of scripting code (whether a full script or just a single
scripting statement in an already existing context). In addition, a notion of binding
between scripting entities and Java was introduced, as well as script engine discov‐
ery. Finally, javax.script provides optional support for invocation (distinct from
execution, as it allows intermediate code to be exported from a scripting language's
runtime and used by the JVM runtime).
The example language provided was Rhino, but many other scripting languages
were created to take advantage of the support provided. With Java 8, Rhino has been
removed, and Nashorn is now the default scripting language supplied with the Java
Introducing javax.script with Nashorn
Let's look at a very simple example of how to use Nashorn to run JavaScript from
import javax.script.* ;
ScriptEngineManager m = new ScriptEngineManager ();
ScriptEngine e = m . getEngineByName ( "nashorn" );
try {
e . eval ( "print('Hello World!');" );
} catch ( final ScriptException se ) {
// ...
The key concept here is ScriptEngine , which is obtained from a ScriptEngineMan
ager . This provides an empty scripting environment, to which we can add code via
the eval() method.
The Nashorn engine provides a single global JavaScript object, so all calls to eval()
will execute on the same environment. This means that we can make a series of
eval() calls and build up JavaScript state in the script engine. For example:
e . eval ( "i = 27;" );
e . put ( "j" , 15 );
e . eval ( "var z = i + j;" );
System . out . println ((( Number ) e . get ( "z" )). intValue ()); // prints 42
Search WWH ::

Custom Search