You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nashorn环境下调用匿名根级函数封装的非main子函数的解决方案求助

Nashorn环境下调用匿名根级函数封装的非main子函数的解决方案求助

我正在给一批JS脚本搭建基础测试框架,这些脚本原本在Nashorn(JDK 11)环境下运行完全没问题,现在我需要自己加载并运行它们,通过输入输出对比来完成测试工作。

目前卡在了脚本的格式问题上——我知道它们能在Nashorn正常运行,但看不到调用这些脚本的源码,现在没法获取到需要的所有函数/方法的引用。这类脚本的结构都遵循以下模式:

(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之外的其他函数我都拿不到引用。不过我倒是通过两次执行的方式成功获取到了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);

当然,如果有更高效的获取main引用的方法,我也非常欢迎。但现在更大的难题是,脚本里封装在匿名函数中的其他函数完全无法访问。运行上面的代码时会抛出以下异常:

Exception in thread "main" <eval>:3 ReferenceError: "writeLogEntry" is not defined. 

我试过几种尝试,比如:

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

不管是在第一次执行之后还是第二次执行之后调用这段代码,都没法成功获取到引用。我还在每次执行后用调试器暂停程序,查看返回的对象,但始终找不到其他方法的引用痕迹。

有没有大佬能给我指点一下,该怎么解析和运行这种格式的脚本?任何建议我都感激不尽!

备注:内容来源于stack exchange,提问作者BogStandard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 10:32:56