Nashorn 将已编译的脚本放入引擎范围

Nashorn put compiledsript into engine scope

我有两个js文件,

在我的项目中,我试图在我的应用程序启动期间预编译所有 javascript,然后在运行时仅调用具有所需参数的 CompiledScripts。

我最终得到了以下代码



    static String LIBRARY = "function hello(arg) {return 'Hello ' + arg;};";

    static String SCRIPT = "hello(arg)";

    public static void main(String... args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn");
        Compilable compilable = ((Compilable) engine);
        CompiledScript compiledLib = compilable.compile(LIBRARY);
        compiledLib.eval();

        CompiledScript actualScript = compilable.compile(SCRIPT);

        Bindings helloParams = new SimpleBindings();
        helloParams.put("arg","world");
        ScriptObjectMirror result = (ScriptObjectMirror) actualScript.eval(helloParams);
        System.out.println(result);
}

但是这段代码会抛出错误

> compiledScript.eval(helloParams);
<eval>:1 ReferenceError: "hello" is not defined

如何从 "actualScript" 中访问 "compiledLib" 的上下文(即方法和变量)?

编译不注册hello()函数,只是解析JavaScript代码

您需要执行注册函数的代码。

请记住,在 JavaScript 中,这两个语句之间几乎没有区别,除了 function 声明被提升,因此可以在声明语句之前使用:

function hello(arg) {return 'Hello ' + arg;};

var hello = function(arg) {return 'Hello ' + arg;};

因此没有理由单独编译 LIBRARY 代码,您只需 运行 它并保存所有创建的全局变量,即库方法。例如。执行您的 LIBRARY 代码后,您将拥有一个名为 hello.

的全局变量
ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn");
Compilable compilable = ((Compilable) engine);

// Process LIBRARY code
Bindings bindings = new SimpleBindings();
engine.eval(LIBRARY, bindings);

// Compile SCRIPT code
CompiledScript actualScript = compilable.compile(SCRIPT);

// Run SCRIPT code
bindings.put("foo", "world");
Object result = actualScript.eval(bindings);
System.out.println(result);

输出

Hello world