Java Reference
In-Depth Information
// Cast the engine reference to the Invocable type
Invocable inv = (Invocable) engine;
try {
String scriptPath1 = "factorial.js";
String scriptPath2 = "avg.js";
// Evaluate the scripts first, so the
// factorial() and avg() functions are
// compiled and are available to be invoked
engine.eval("load('" + scriptPath1 + "');");
engine.eval("load('" + scriptPath2 + "');");
// Invoke the add function twice
Object result1 = inv.invokeFunction("factorial", 10);
System.out.println("factorial(10) = " + result1);
Object result2 = inv.invokeFunction("avg", 10, 20, 30);
System.out.println("avg(10, 20, 30) = " + result2);
}
catch (ScriptException | NoSuchMethodException e) {
e.printStackTrace();
}
}
}
factorial(10) = 3628800.0
avg(10, 20, 30) = 20.0
An object-oriented or object-based scripting language may let you define objects and
their methods. You can invoke methods of such objects using the invokeMethod(Object
obj, String name, Object... args) method of the Invocable interface. The first
argument is the reference of the object, the second argument is the name of the method
that you want to invoke on the object, and the third argument is a varargs argument that
is used to pass arguments to the method being invoked.
Listing 5-2 contains a Nashorn script that creates an object named calculator and
adds four methods to add, subtract, multiply, and divide two numbers. Notice that I have
used the Nashorn syntax extension to define the function expressions in which the braces
and return statements are not specified.
Search WWH ::




Custom Search