So far I only know that it is an interface that has the following methods:
invokeMethod()
invokeFunction()
getInterface()
But I don't understand what each of them is for and where exactly the Invocable interface is used.
So far I only know that it is an interface that has the following methods:
invokeMethod()
invokeFunction()
getInterface()
But I don't understand what each of them is for and where exactly the Invocable interface is used.
This interface is used in machines that interpret other programming languages such as
javascript
, which is done with Nashorn, for example.Imagine you have javascript like:
With the script engine you implement the interface
Invocable
to call functions from Java with invokeFunction() :We can also create interfaces in java with getInterface() to access the script:
The last invokeMethod() method is similar to
invokeFunction
but allows you to call methods of an object:Nashorn documentation in English (Oracle)
When a script engine (which implements
javax.script.ScriptEngine
) also implements the interfacejavax.script.Invocable
, it means that it can execute procedures, functions or methods that have previously been compiled .That is, instead of using the method
eval
,javax.script.ScriptEngine
you can call the procedure or function or method directly from a Java program. Note that implementation of the interfaceInvocable
by a script engine is optional. Before calling any procedure, function, or method, check if the script engine is an instance of this interface, cast aInvocable
, and then execute the methods of this interface.This interface contains four methods. Both versions of the method
getInterface()
allow obtaining an instance of a Java interface which is implemented in a scripting language (eg:factorial.js
). The methodinvokeFunction()
allows you to call a higher-level function (eg:parseInt()
) written in a scripting language . The methodinvokeMethod()
allows calling methods of objects (eg:obj.toString()
) written in a scripting language .If you want to make an invocation of this type, you can follow the following steps:
First check if the script engine is
Invocable
:Cast the reference to
ScriptEngine
aInvocable
:Evaluate a script for the engine to compile and save the compiled for future invocations:
Invoke the procedure, function, or method:
addition
A script engine can also implement the interface
javax.script.Compilable
which allows scripts to be compiled for repeated execution.References