Java Reference
In-Depth Information
Method
Description
Returns an implementation of an interface using the func-
tions compiled by the interpreter.
getInterface(Class<T>)
Returns an implementation of an interface using member
functions of a scripting object that has been compiled in
the interpreter.
getInterface(Object,
Class<T>)
Calls on top-level procedures and functions. Returns an
object.
invokeFunction(String,
Object)
Calls a method on a script object that was compiled during
a previous execution.
invokeFunction(Object,
String, Object)
Before an
Invocable
can be generated, the JavaScript file or function must be
evaluated by the
ScriptEngine
. The example demonstrates calling on the
eval()
method to evaluate an in-line JavaScript function (a string named
gallonsFunc-
tion
), and it shows how to evaluate an external JavaScript file. Once the
eval()
method has been called, the
ScriptEngine
can be coerced into an
Invocable
ob-
ject, as follows:
Invocable inv = (Invocable) engine;
Invocable
can then be called upon to execute functions or methods within the
In this recipe's examples, the
invokeFunction
method is used to call on the
functions contained in the script. The first argument to
invokeFunction
is the
string-based name of the function being called upon, and the second argument is a list
of
Object
s that are being passed as arguments. The
Invocable
returns an
Object
from the JavaScript function call, which can be coerced into the appropriate Java type.
Sharing values between Java and
ScriptEngine
instances is very useful. In a
real-life scenario, it may be very useful to call on an external JavaScript file, and have
the ability to pass values back and forth between the Java code and the script. The un-
derlying JavaScript file can be modified, if needed, without recompiling the applica-
tion. This situation can be very useful when your application contains some business
logic that needs to change from time to time. Imagine that you have a rules processor
that can be used to evaluate strings, and the rules are constantly evolving. In this case,
the rule engine can be written as an external JavaScript file, enabling dynamic changes
to that file.