Java Reference
In-Depth Information
Instantiating the Nashorn Engine
In previous chapters, you have been instantiating the Nashorn engine in Java code using
the standard Java Scripting API. The Nashorn engine provides several custom features. To
take advantage of those features, you will need to instantiate the Nashorn engine directly.
First, you will need to create an object of the NashornScriptEngineFactory class, and
then call one of the overloaded versions of the getScriptEngine() method to create a
Nashorn engine:
// Create a Nashorn engine factory
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
// Create a Nashorn engine with default options
ScriptEngine engine = factory.getScriptEngine();
By default, the Nashorn engine factory creates a Nashorn engine with the --dump-
on-error option enabled. I will show you how to set other options for the Nashorn engine
in the next example.
The following snippet of code creates a Nashorn engine with the --no-java and
-strict options:
// Create a Nashorn engine factory
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
// Store the Nashorn options in a String array
String[] options = {"--no-java", "-strict"};
// Create the Nashorn engine with the options
ScriptEngine engine = factory.getScriptEngine(options);
Because of the --no-java option, you cannot use any Java classes inside the scripts
executed by this engine. The -strict option will force the engine to execute all scripts in
strict mode.
You can also pass options to the Nashorn engine using the nashorn.args system
property on the command-line. The following command runs the com.jdojo.script.
Test class, passing four options to the Nashorn engine:
java -Dnashorn.args="--global-per-engine -strict --no-java --language=es5"
com.jdojo.script.Test
Notice that options are separated by a space and they all are passed as one string.
If you have only one option to pass, you can omit the double quotes around the option's
value. The following command passes only one option, --no-java , to the engine:
java -Dnashorn.args=--no-java com.jdojo.script.Test
 
Search WWH ::




Custom Search