通过使用 Java Sripting API,我能够在 Java 中执行 JavaScript。但是,有人可以解释如何从 Java 中的 JS 捕获返回值吗?在下面的示例中,我可以使用调用 script2
inv.invokeFunction("getValue", "Number", "2);
如何从 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.
}
}