java - Nashorn 将compiledsript 放入引擎范围
问题描述
我有两个js文件,
- 一个是js库
- 第二个是一个简单的脚本,通常大约 50 行,需要访问库中的函数。
在我的项目中,我试图在我的应用程序启动期间预编译所有 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
推荐阅读
- node.js - 创建一个 post 表,将 userID 添加到 post 表中,并将 postID 自动添加到 sequlize 中的 image 表中
- wpf - 从类库 (dll) 运行 wpf 应用程序
- jquery - jquery自动完成设置隐藏输入值
- java - 为什么我得到 MimeBodyPart 类型的 attachFile(File) 未定义?
- java - OnItemLongClickListener 在 Firebase 数据库填充的 ListView 上不起作用
- php - 根据存储在数据库 MySQL 中的日期时间发送推送通知
- python - 将 Pandas 数据框单元格转换为列表
- python - 获取具有给定总和的所有子集的递归程序包括重复
- ios - 何时将用户注册数据保存到 Cloud Firestore
- r - 求解 50 个非线性方程组 - fn(par,...) 中的错误:缺少参数