我正在使用Java 8 Nashorn来执行一个特定的先前约定的方法。我可以调用特定的方法,没有问题。但有一件事困扰着我,那就是当我加载脚本时,它也会执行它。
例如,如果file.js包含打印(“hello world!")ScriptEngine.eval(新的FileReader("./file.js")将执行并打印hello world。在我可以调用我想要的特定方法之前,我必须这样做。
有没有办法在不执行脚本的情况下对脚本执行/load()?
谢谢
发布于 2016-03-20 06:21:34
事实证明,您可以通过将引擎强制转换为可编译,然后调用编译函数来完成此操作。
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()
https://stackoverflow.com/questions/36073136
复制相似问题