Java Reference
In-Depth Information
You want to invoke a JavaScript function and return the result to the Java class that in-
voked it.
Solution
Create a ScriptEngine for use with Nashorn and then pass the JavaScript function
to it for evaluation. Next, create an Invocable from the engine and then call its in-
vokeFunction() method, passing the string-based name of the JavaScript function,
along with an array of the arguments to be used. In the following example, a JavaScript
function named gallons is passed to the ScriptEngine for evaluation, and it is
later invoked using this technique. It then returns a double value.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
// JavaScript code in a String
String gallonsFunction = "function gallons(width, length,
avgDepth){var volume = avgDepth * width * length; "
+ " return volume * 7.48; } ";
try {
// evaluate script
engine.eval(gallonsFunction);
double width = 16.0;
double length = 32.0;
double depth = 5.0;
Invocable inv = (Invocable) engine;
double returnValue = (double)
inv.invokeFunction("gallons",
new
Double[]{width,length,depth});
System.out.println("The returned value:"
+ returnValue);
} catch (ScriptException | NoSuchMethodException ex) {
Logger.getLogger(Recipe18_5.class.getName()).log(Level.SEVERE,
null, ex);
}
Search WWH ::




Custom Search