almost 4 years ago
It is quite straight forward but there are several steps that one needs to follow:
Packages you will need to import
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.Invocable;
import javax.script.ScriptException;
Steps:
- Create a ScriptEngineManager object
- Call the object's
getEngineByName
passing it the string "JavaScript". This will create a script engine object. - Call the engine object's eval method and pass it a valid JavaScript string (you can read it in from a file)
- Cast the engine object as Invocable
- Call the invocable engine object's
invokeFunction
and pass it the name of your JavaScript function (not the file) and the list of parameters all seperated by commas. - Received the result in an Object variable and then cast it to the expected object.
Example Java
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.Invocable;
import javax.script.ScriptException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
class Examples {
public static String getScript(String fn) {
String fileContentAsString="";
try {
fileContentAsString = new String(Files.readAllBytes(Paths.get(fn)));
}
catch (IOException ie) {
System.err.println (ie.getMessage());
}
return fileContentAsString;
}
public static String scriptCall () {
ScriptEngineManager manager = new ScriptEngineManager(); // step 1
ScriptEngine engine = manager.getEngineByName("JavaScript"); // step 2
Object result = null;
try {
engine.eval(getScript("test.js")); // step 3
Invocable inv = (Invocable) engine; // step 4
result = inv.invokeFunction("call_me", "3", "2"); // step 5
} catch(ScriptException se) {
System.err.println (se.getMessage());
}
catch(NoSuchMethodException nse) {
System.err.println (nse.getMessage());
}
return result.toString(); // step 6 maybe optional
}
public static void main(String[] args) {
System.out.println (scriptCall());
}
}
The Javascript file
function call_me (p1,p2){
var s = p1 * p2
return s
}