Java Reference
In-Depth Information
The third step is to evaluate the script, so the script engine compiles and stores
the compiled form of the procedure for later invocation. The following snippet of code
performs this step:
// Declare a function named add that adds two numbers
String script = "function add(n1, n2) { return n1 + n2; }";
// Evaluate the function. Call to eval() does not invoke the function.
// It just compiles it.
engine.eval(script);
The last step is to invoke the procedure, as shown:
// Invoke the add function with 30 and 40 as the function's arguments.
// It is as if you called add(30, 40) in the script.
Object result = inv.invokeFunction("add", 30, 40);
The first argument to the invokeFunction() is the name of the procedure. The
second argument is a varargs that is used to specify arguments to the procedure. The
invokeFunction() method returns the value returned by the procedure.
Listing 5-1 shows how to invoke a function. It invokes a function written in Nashorn
JavaScript. It loads the scripts in the files named factorial.js and avg.js . These files
contain the Nashorn code for the functions named factorial() and avg() . Later, the
program invokes these function using the invokeFunction() of the Invocable interface.
Listing 5-1. Invoking a Function Written in Nashorn JavaScript
// InvokeFunction.java
package com.jdojo.script;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class InvokeFunction {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// Make sure the script engine implements the Invocable
// interface
if (!(engine instanceof Invocable)) {
System.out.println(
"Invoking procedures is not supported.");
return;
}
 
Search WWH ::




Custom Search