Java Reference
In-Depth Information
The second code example demonstrates how to write and evaluate inline
JavaScript. First, a function identified as gallons is defined and it accepts three para-
meters and returns the number of gallons based on the width, length, and average depth
of a pool. In a subsequent eval() call, the function is invoked, passing parameters
and returning a result. The important point to note in this example is that although the
JavaScript spanned multiple eval() calls, the scope is maintained so that each ev-
al() call within the engine can see objects created within previous calls.
Since Java 6, it has been possible to work with scripting languages from within
Java code. The Nashorn engine is obtained in the same manner as others, by passing a
string to indicate the engine by name. The difference between this JavaScript engine
and the previous rendition Rhino is that the new JavaScript engine is much faster and
provides better compliance with the EMCA-normalized JavaScript specification.
18-2. Executing JavaScript via the Com-
mand Line
Problem
You want to execute JavaScript via the command line for prototyping or execution pur-
poses.
Solution 1
Invoke the jjs tool, which comes as part of Java 8. To execute a JavaScript file, in-
voke the jjs tool from the command line, and then pass the fully qualified name (path
included if not in CLASSPATH ) of a JavaScript file to execute. For example, to execute
helloNashorn.js , use the following command:
jjs /src/org/java8recipes/chapter18/js/helloNashorn.js
Hello Nashorn!
To pass arguments to a JavaScript file for processing, call the script in the same
manner, but include trailing dashes -- , followed by the argument(s) you want to pass.
For example, the following code resides within a file named helloParameter.js :
Search WWH ::




Custom Search