Java Reference
In-Depth Information
Passing Arguments to Scripts
The
jrunscript
shell allows passing arguments to scripts. The arguments are made
available to the script in an array-like object named
arguments
. You can access the
arguments
array inside the script in a language-specific way. The following command
passes three arguments of 10, 20, and 30, and prints the value of the first argument:
C:\>jrunscript -e "print('First argument is ' + arguments[0])" 10 20 30
First argument is 10
Consider the Nashorn JavaScript file
nashornargstest.js
shown in Listing 9-2,
which prints the number of arguments and their values that are passed to the script.
Listing 9-2.
A nashornargstest.js File Written in Nashorn JavaScript to Print
Command-Line Arguments
// nashornargstest.js
print("Number of arguments:" + arguments.length);
print("Arguments are ") ;
for(var i = 0; i < arguments.length; i++) {
print(arguments[i]);
}
The following commands run the
nashornargstest.js
file using the
jrunscript
shell:
C:\>jrunscript nashornargstest.js
Number of arguments:0
Arguments are
C:\>jrunscript nashornargstest.js 10 20 30
Number of arguments:3
Arguments are
10
20
30
If you want to run the
nashornargstest.js
file from a Java application, you need to
pass an argument named
arguments
to the engine. The argument named
arguments
is
passed to the script by the shell automatically, not by a Java application.
Search WWH ::
Custom Search