Java Reference
In-Depth Information
// Get the Nashorn script engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
try {
// Get a Reader for the script file
Reader scriptReader = Files.
newBufferedReader(scriptPath);
// Execute the script in the file
engine.eval(scriptReader);
}
catch (IOException | ScriptException e) {
e.printStackTrace();
}
}
}
Hello from JavaScript!
In a real-world application, you should store all scripts in files that allow modifying
scripts without modifying and recompiling your Java code. You will not follow this rule in
most of the examples in this chapter; you will store your scripts in String objects to keep
the code short and simple.
Passing Parameters
The Java Scripting API allows you to pass parameters from the host environment (Java
application) to the script engine and vice versa. In this section, you will see the technical
details of parameter passing mechanisms between the host application and the script
engine. There are several way to pas parameters to scripts from Java programs. In this
chapter, I will explain the simplest form of parameter passing. I will discuss all other
forms in Chapter 3.
Passing Parameters from Java Code to Scripts
A Java program may pass parameters to scripts. A Java program may also access global
variables declared in a script after the script is executed. Let's discuss a simple example
of this kind where a Java program passes a parameter to a script. Consider the program in
Listing 2-3 that passes a parameter to a script.
 
Search WWH ::




Custom Search