Reputation: 73
By using Java Sripting API, I am able to execute JavaScript within Java. However, can someone please explain how to capture the return value from a JS in Java? In the example below, can I invoke the script2 using
inv.invokeFunction("getValue", "Number", "2);
How can I get the return value from script2?
import javax.script.*;
public class InvokeScriptFunction {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// JavaScript code in a String
String script1 = "function hello(name) {print ('Hello, ' + name);}";
String script2 = "function getValue(a,b) { if (a==="Number") return 1;
else return b;}";
// evaluate script
engine.eval(script1);
engine.eval(script2);
Invocable inv = (Invocable) engine;
inv.invokeFunction("hello", "Scripting!!" ); //This one works.
}
}
Upvotes: 3
Views: 8791
Reputation: 46900
This is how you will get that return value.
String returnValue = (String)inv.invokeFunction("hello", "Scripting!!" );
Same for script 2, just change the call accordingly.
The invokeFuntion method from Invocable returns an Object. So, we must type-cast it to the appropriate type before using it.
Upvotes: 6