Java Reference
In-Depth Information
calling the toString() method of the variable msg . Change the statement that assigns the
value to the script variable in Listing 2-3 to the following and run the program, which
will produce the same output:
String script = "println(msg.toString())";
Passing Parameters from Scripts to Java Code
A script engine may make variables in its global scope accessible to Java code. The
get(String variableName) method of a ScriptEngine is used to access those variables
in Java code. It returns a Java Object . The declaration of a global variable is scripting-
language-dependent. The following snippet of code declares a global variable and assigns
it a value in JavaScript:
// Declare a variable named year in Nashorn
var year = 1969;
Listing 2-4 contains a program that shows how to access a global variable in Nashorn
from Java code.
Listing 2-4. Accessing Script Global Variables in Java Code
// AccessingScriptVariable.java
package com.jdojo.script;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class AccessingScriptVariable {
public static void main(String[] args) {
// Get the Nashorn engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// Write a script that declares a global variable named year
// and assign it a value of 1969.
String script = "var year = 1969";
try {
// Execute the script
engine.eval(script);
// Get the year global variable from the engine
Object year = engine.get("year");
 
Search WWH ::




Custom Search