【问题标题】:Java 8 Nashorn load script without executing itJava 8 Nashorn 加载脚本而不执行它
【发布时间】:2016-07-04 13:03:21
【问题描述】:

我正在使用 Java 8 Nashorn 来执行特定的先前商定的方法。我可以调用特定的方法没问题。不过让我烦恼的一件事是,当我加载脚本时,它也会执行它。

例如,如果 file.js 包含 print("hello world!"),则 scriptEngine.eval(new FileReader("./file.js") 将执行并打印 hello world。我必须先执行此操作调用我想要的具体方法。

有没有办法在不执行的情况下评估()/加载脚本?

谢谢

【问题讨论】:

  • “有没有办法在不执行的情况下加载脚本?” 这个操作的结果是什么?您只想获取源文本吗?在这种情况下,只需使用 FileReader? 读取文件?
  • 我想最终调用一个特定的方法,但是如果没有事先调用 .eval() 来执行脚本,我就无法做到这一点:(

标签: nashorn


【解决方案1】:

原来你可以通过将引擎转换为 Compilable 然后调用 compile 函数来做到这一点。

final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
final Compilable compilable = (Compilable) engine;
        final Invocable invocable = (Invocable) engine;
        final String statement = "function fetch(values) { return values['first_name'] + ' ' + values['last_name']; };";
        final CompiledScript compiled = compilable.compile(statement);

这实现了我想要的,而无需 eval()

【讨论】:

    猜你喜欢
    • 2012-06-21
    • 2010-12-30
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    相关资源
    最近更新 更多