Java Reference
In-Depth Information
Here's the result:
run:
The returned value:19148.800000000003
In the following example, a JavaScript file is invoked and returns a string value.
The name of the JavaScript file is recipe18_5.js and its contents are as follows:
function returnName( name){
return "Hello " + name;
}
Next, use the ScriptEngine to create an Invocable and call on the
JavaScript function within the external JavaScript file.
engine.eval("load('/path-to/src/org/java8recipes/
chapter18/recipe18_05/js/recipe18_5.js')");
Invocable inv2 = (Invocable) engine;
String returnValue2 = (String)
inv2.invokeFunction("returnName", new
String[]{"Nashorn"});
System.out.println("The returned value:" + returnValue2);
How It Works
One of the most useful features of embedded scripting is the ability to integrate the
code invoked via a script engine along with a Java application. In order to effectively
integrate script engine code and Java code, the two must be able to pass values to each
other. This recipe covers the concept of returning values from JavaScript back to Java.
To do so, set up a ScriptEngine and then coerce it into a
javax.script.Invocable object. The Invocable object can then be used to
execute script functions and methods, returning values from those invocations.
An Invocable object enables you to execute a named JavaScript function or
method and return values to the caller. Invocable can also return an interface that
will provide a way to invoke the member functions of the scripting object. To provide
this functionality, the Invocable object contains several methods (see Table 18-1 ).
Table 18-1 . Invocable methods
 
 
Search WWH ::




Custom Search