This code demonstrate the use of Invocable
interface to invoke a specific function of a script. The Invocable.invokeFunction()
takes the function name with or without a parameter as the function’s parameter. The parameter value can be passed as a varargs
.
package org.kodejava.script;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import javax.script.Invocable;
public class InvokingFunction {
public static void main(String[] args) {
String script = """
function sayHello() {
sayHello(null);
}
function sayHello(name) {
print('Hi there' + ((name == null) ? '!' : ' ' + name + '!'));
}
""";
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension("js");
try {
engine.eval(script);
// Convert / cast the engine into invocable engine.
Invocable invocableEngine = (Invocable) engine;
// Invoking sayHello function without parameter.
invocableEngine.invokeFunction("sayHello");
// Invoking sayHello function with a parameter.
invocableEngine.invokeFunction("sayHello", "Jude");
} catch (ScriptException | NoSuchMethodException e) {
e.printStackTrace();
}
}
}
This will output:
Hi there!
Hi there Jude!
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.graalvm.js</groupId>
<artifactId>js</artifactId>
<version>22.3.2</version>
</dependency>
<dependency>
<groupId>org.graalvm.js</groupId>
<artifactId>js-scriptengine</artifactId>
<version>22.3.2</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024