我正在尝试通过Java调用JavaScript中的函数。这在直接将脚本作为字符串读取时工作正常,但我正在使用CompiledScripts。
当我使用编译的脚本执行此操作时,如果我还添加了绑定,则会为我提供找不到的方法。没有绑定它可以工作但当然函数失败,因为它需要绑定。
有什么想法吗?
CompiledScript script = ... get script....
Bindings bindings = script.getEngine().createBindings();
Logger scriptLogger = LogManager.getLogger("TEST_SCRIPT");
bindings.put("log", scriptLogger);
//script.eval(bindings); -- this way fails
script.eval(); // -- this way works
Invocable invocable = (Invocable) script.getEngine();
invocable.invokeFunction(methodName);
TIA
答案 0 :(得分:10)
如果有其他人碰到这个问题,这就是解决方案。
import java.util.*;
import javax.script.*;
public class TestBindings {
public static void main(String args[]) throws Exception {
String script = "function doSomething() {var d = date}";
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
Compilable compilingEngine = (Compilable) engine;
CompiledScript cscript = compilingEngine.compile(script);
//Bindings bindings = cscript.getEngine().createBindings();
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
for(Map.Entry me : bindings.entrySet()) {
System.out.printf("%s: %s\n",me.getKey(),String.valueOf(me.getValue()));
}
bindings.put("date", new Date());
//cscript.eval();
cscript.eval(bindings);
Invocable invocable = (Invocable) cscript.getEngine();
invocable.invokeFunction("doSomething");
}
}