5

我正在尝试通过 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

4

1 回答 1

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");
    }
}
于 2010-04-26T15:23:53.867 回答