Java Reference
In-Depth Information
Listing 5-2. A Calculator Object Created in Nashorn Script
// calculator.js
// Create an object
var calculator = new Object();
// Add four methods to the prototype to the calculator object
calculator.add = function (n1, n2) n1 + n2;
calculator.subtract = function (n1, n2) n1 - n2;
calculator.multiply = function (n1, n2) n1 * n2;
calculator.divide = function (n1, n2) n1 / n2;
Listing 5-3 demonstrates the invocation of a method on the calculator object that
is created in Nashorn. Note that the object is created inside the Nashorn script. To invoke
the method of the object from Java, you need to obtain the reference of the object through
the script engine. The program evaluates the script in the calculator.js file that creates
the calculator object and stores its reference in a variable named calculator . The
engine.get("calculator") method returns the reference of the calculator object to the
Java code.
Listing 5-3. Invoking a Method on an Object Created in Nashorn
// InvokeMethod.java
package com.jdojo.script;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class InvokeMethod {
public static void main(String[] args) {
// Get the Nashorn engine
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 methods is not supported.");
return;
}
// Cast the engine reference to the Invocable type
Invocable inv = (Invocable) engine;
 
Search WWH ::




Custom Search