nashorn:用匿名的根级函数和子功能执行脚本

问题描述 投票:0回答:1
(function () { "use strict"; print("Canary: Here I am inside the root level function"); function writeLogEntry(message) { echo(message); } return function main(data) { print("Canary: Here I am inside main"); writeLogEntry(data.someVitalStat()); return true; }; })();

我没有更改源文件的选项 - 我必须使用它们。问题在于获得除main以外的功能的引用。我能够通过以下方式获得主要的裁判,这需要两次通过:

String scriptTextRaw = new String(Files.readAllBytes(Paths.get(location)), StandardCharsets.UTF_8); var ee = new ScriptEngineManager().getEngineByName("Nashorn"); scriptTextRaw = "var mainfunc = " + scriptTextRaw; ee.eval(scriptTextRaw); Object mainRef = ee.get("mainfunc"); // Second eval pass ee.eval(mainRef.toString()); var mainInvocable = (ScriptObjectMirror)ee.get("main"); // Invoke main function Object mainResult = mainInvocable.call(myDataObject);

我对获得该主要参考的更好方法开放。但是,更大的问题是封装在脚本中的匿名函数无法访问。运行上述代码,我得到:
Exception in thread "main" <eval>:3 ReferenceError: "writeLogEntry" is not defined. 

我尝试了一些事情,例如:

Object writeLogEntryRef = (ScriptObjectMirror)ee.get("writeLogEntry"); 

(第一和第二次评估之后)

但这是不成功的。每次评估通过以检查返回的对象后,我还暂停了调试器中的程序,但我找不到对其他方法的任何参考。
有人可以建议一种解析和运行像这样格式的脚本的方法吗?所有的输入都非常感谢。

经常发生,写了一个问题,赋予了我回答它的见解。这里的根问题是我奇怪的两次通行方法,我认为这对于获取返回的主函数的引用是必要的。取而代之的是,我尝试省略我已经预先预先预先的“ var mainref =”字符串,然后从第一个通过的结果中调用
call

ScriptEngine ee = new ScriptEngineManager().getEngineByName("Nashorn"); String scriptTextRaw = new String(Files.readAllBytes(Paths.get(location)), StandardCharsets.UTF_8); Object pass1Result = ee.eval(scriptTextRaw); System.out.println(((ScriptObjectMirror) pass1Result).call("main", "blah"));

使用此方法,当调用主函数时,对其他功能的调用成功。

javascript java ecmascript-5 nashorn
1个回答
0
投票
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.