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);

ティア

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 に答える