Java Reference
In-Depth Information
The Nashorn scripting engine can be invoked in two ways:
By embedding the engine in the JVM
jjs command-line tool
In this chapter, I will discuss both ways of using the Nashorn script engine.
By using the
Executing Your First Script
In this section, you will use Nashorn to print a message on the standard output. You
will access the Nashorn engine from Java code. The same steps can be used to print a
message using any other scripting languages, with one difference: you will need to use the
scripting language-specific code to print the message. You need to perform three steps to
run a script in Java:
Create a script engine manager.
Get an instance of a script engine from the script engine manager.
eval() method of the script engine to execute a script.
A script engine manager is an instance of the ScriptEngineManager class. You can
create a script engine, like so:
Call the
// Create a script engine manager
ScriptEngineManager manager = new ScriptEngineManager();
An instance of the ScriptEngine interface represents a script engine in a
Java program. The getEngineByName(String engineShortName) method of a
ScriptEngineManager is used to get an instance of a script engine. To get an instance of
the Nashorn engine, use JavaScript as the short name of the engine as shown:
// Get the reference of a Nashorn engine
ScriptEngine engine = manager.getEngineByName("JavaScript");
the short name of a script engine is case-sensitive. Sometimes a script engine has
multiple short names. nashorn engine has the following short names: nashorn , Nashorn ,
js , JS , JavaScript , javascript , ECMAScript , ecmascript . You can use any of the short
names of an engine to get its instance using the getEngineByName() method of the
ScriptEngineManager class.
Tip
 
 
Search WWH ::




Custom Search