简体   繁体   English

如何在Nashorn CompiledScript中调用方法?

[英]How do you invoke a method in a Nashorn CompiledScript?

I have the following code which works: 我有以下有效的代码:

ScriptEngine jsEngine = ScriptEngineManager.new().getEngineByName("nashorn");
jsEngine.eval("some script");

jsEngine.invokeMethod(jsEngine.eval("foo"), "bar");

but I want to do use a pre-compiled script so I don't have to evaluate the script every time I need to run it, so I'm trying; 但是我想使用预编译的脚本,因此我不必每次都需要运行该脚本时对其进行评估,因此我正在尝试;

ScriptEngine jsEngine = ScriptEngineManager.new().getEngineByName("nashorn");
CompiledScript compiledJS = jsEngine.compile("some script");

but then I'm not sure what to do with CompiledScript, how do I invoke a method? 但是我不确定该如何处理CompiledScript,如何调用方法? it doesn't implement anything else than eval() apparently: https://docs.oracle.com/javase/8/docs/api/javax/script/CompiledScript.html 它显然没有实现eval()以外的任何其他功能: https : //docs.oracle.com/javase/8/docs/api/javax/script/CompiledScript.html

You call the method? 你叫方法?

Here are few examples: http://www.programcreek.com/java-api-examples/index.php?api=javax.script.CompiledScript 以下是一些示例: http : //www.programcreek.com/java-api-examples/index.php? api= javax.script.CompiledScript


Example: 例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM