在Java编译的脚本中调用Javascript函数's编写API脚本

Invoking a Javascript function in a compiled script in Java's Script API

本文关键字:脚本 API 编写 函数 Javascript 编译 Java 调用      更新时间:2023-09-26

我有一些代码可以成功地加载和编译脚本。这很有效。不过,接下来,我希望能够在编译后的脚本中调用一个函数。不幸的是,我看不出有任何方法可以调用编译后的脚本。

Compilable compEngine = (Compilable)engine;
compiledScripts.put(filename, compEngine.compile(new InputStreamReader(in)));
compiledScripts.get(filename).eval();
//All works until this point. The compiled script does not seem to be invokable.
Invocable inv = (Invocable) compiledScripts.get(filename);
inv.invokeFunction("onLoad");

有办法做到这一点吗?如果是,如何?如果没有,在不编译脚本时,他们的性能通常会受到多大影响?

我找到了问题的答案。这实际上是一个非常简单的改变。

此行:

Invocable inv = (Invocable) compiledScripts.get(filename);

需要更改为:

Invocable inv = (Invocable) compiledScripts.get(filename).getEngine();

这将返回已编译脚本正在运行的引擎,从而允许我们从已编译脚本中调用函数。