Java Reference
In-Depth Information
Listing 2-3. Passing Parameters From a Java Program to Scripts
// PassingParam.java
package com.jdojo.script;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class PassingParam {
public static void main(String[] args) {
// Get the Nashorn engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// Store the script in a String. Here, msg is a variable
// that we have not declared in the script
String script = "print(msg)";
try {
// Store a parameter named msg in the engine
engine.put("msg", "Hello from Java program");
// Execute the script
engine.eval(script);
}
catch (ScriptException e) {
e.printStackTrace();
}
}
}
Hello from Java program
The program stores a script in a String object as follows:
// Store a Nashorn script in a String object
String script = "print(msg)";
In the statement, the script is:
print(msg)
Note that msg is a variable used in the print() function call. The script does not
declare the msg variable or assign it a value. If you try to execute the above script without
telling the engine what the msg variable is, the engine will throw an exception stating
 
Search WWH ::




Custom Search