Java Reference
In-Depth Information
Chapter 2
Executing Scripts
In this chapter, you will learn:
eval()
method of
ScriptEngine
to execute scripts
•
How to use the
•
How to pass parameters from Java code to Nashorn engine
•
How to pass parameters from Nashorn engine to Java
Using the eval( ) Method
A
ScriptEngine
can execute a script in a
String
and a
Reader
. Using a
Reader
, you can
execute a script stored on the network or in a file. One of the following versions of the
eval()
method of the
ScriptEngine
interface is used to execute a script:
Object eval(String script)
•
Object eval(Reader reader)
•
Object eval(String script, Bindings bindings)
•
Object eval(Reader reader, Bindings bindings)
•
Object eval(String script, ScriptContext context)
•
Object eval(Reader reader, ScriptContext context)
The first argument of the
eval()
method is the source of the script. The second
argument lets you pass information from the host application to the script engine that can
be used during the execution of the script.
In Chapter 1, you saw how to use a
String
object to execute a script using the first
version of the
eval()
method. In this chapter, you will store your script in a file and
use a
Reader
object as the source of the script, which will use the second version of the
eval()
method. The next section discusses the other four versions of the
eval()
method.
Typically, a script file is given a
.js
extension.
•
Search WWH ::
Custom Search