使用 Java 和 Nashorn 编写脚本的新手,有教程吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22644441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:03:12  来源:igfitidea点击:

New to scripting with Java and Nashorn, any tutorials?

javajavascriptjava-8nashorn

提问by Michael Yousef

Are there any good tutorials or the likes for getting stated with this? I have yet to do any scripting in Java, though I am familiar with JavaScript already. Thanks. Essentially, I want to use JavaScript/XML to handle part of my project. I know Java 8 introduced JavaScript support via Nashorn. I want to learn how this works. I know it involves using javax.script, but I don't know how that package works nor do I understand how Nashorn works.

是否有任何好的教程或类似的东西来说明这一点?虽然我已经熟悉 JavaScript,但我还没有用 Java 编写任何脚本。谢谢。本质上,我想使用 JavaScript/XML 来处理我的项目的一部分。我知道 Java 8 通过 Nashorn 引入了 JavaScript 支持。我想了解这是如何工作的。我知道它涉及使用 javax.script,但我不知道该包是如何工作的,也不了解 Nashorn 是如何工作的。

回答by Kong

Nashorn is accessed through the standard Java JSR 223 scripting APIs.

Nashorn 是通过标准 Java JSR 223 脚本 API 访问的。

A good generic example is here:

一个很好的通用示例在这里:

http://www.drdobbs.com/jvm/jsr-223-scripting-for-the-java-platform/215801163

http://www.drdobbs.com/jvm/jsr-223-scripting-for-the-java-platform/215801163

Nashorn specific guidance is here:

Nashorn 的具体指导在这里:

https://wiki.openjdk.java.net/display/Nashorn/Nashorn+jsr223+engine+notes

https://wiki.openjdk.java.net/display/Nashorn/Nashorn+jsr223+engine+notes

Here's an example from my code loading static library scripts and building an Invocable custom function:

这是我的代码加载静态库脚本并构建 Invocable 自定义函数的示例:

public class ScriptRunner {
    private static final Logger log = LoggerFactory.getLogger(ScriptRunner.class);
    private static final String ENGINE = "nashorn";
    private String functions;

    public ScriptRunner() throws IOException {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[]  resources = resolver.getResources("your/class/path/*.js");
        log.debug("Found {} script resources", resources.length);
        StringBuilder functions = new StringBuilder();
        for (Resource resource : resources) {
            functions.append(IOUtils.toString(resource.getInputStream()));
        }
        this.functions = functions.toString();
    }

    /**
     * Build an Invocable script.
     * @param script The function code.
     * @return Compiled, invocable script.
     */
    public Invocable buildInvocable(String script) throws ScriptException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName(ENGINE);
        engine.eval(functions);
        engine.eval(script);
        return (Invocable) engine;
    }

}

回答by Vik Gamov

Recently, I did couple presentations on Java and JavaScript (via Nashorn). You can find my slides and examples here.

最近,我做了几个关于 Java 和 JavaScript 的演讲(通过 Nashorn)。您可以在此处找到我的幻灯片和示例。

Here is a very simple script runner implementation

这是一个非常简单的脚本运行器实现

import javax.script.*;

public class ScriptRunner {
    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
        String scriptName = args[0];
        Bindings bindings = nashorn.createBindings();
        bindings.put("scriptFileName", scriptName);
        nashorn.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        nashorn.eval("load('src/main/resources/javascript/' + scriptFileName)");
    }

}

}

test.js that you can pass as an application parameter.

test.js 可以作为应用程序参数传递。

print("This is hello from test.js");

Also, there is a tool jjsthat comes with JDK8. It's CLI JavaScript interpreter. It can be used to write shell scripts in JavaScript and Java. (Good SO advicehow to improve jjson osx, linux). Here is an example of such script

另外,jjsJDK8 附带了一个工具。它是 CLI JavaScript 解释器。它可用于在 JavaScript 和 Java 中编写 shell 脚本。(关于如何改进jjsosx、linux 的好建议)。这是此类脚本的示例

#!/usr/local/bin/jjs -scripting

var currentDir = new java.io.File('.'),
    allFiles = currentDir.list();
print(currentDir.getCanonicalPath());
for (var i = 0; i < allFiles.length; i++) {
    print(allFiles[i]);
}

Feel free to ask question if you have any.

如果您有任何问题,请随时提问。

Thanks,

谢谢,

Vik

维克

回答by Marcus

Here is a nice, very basic "getting started" video:

这是一个很好的,非常基本的“入门”视频:

https://www.youtube.com/watch?v=Cxyg22C5gcw

https://www.youtube.com/watch?v=Cxyg22C5gcw

Julien Ponge has also written a good introductory article:

Julien Ponge 也写了一篇很好的介绍性文章:

http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html

http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html

I would also recommend the Nashorn Wiki for the formal documentation:

我还推荐 Nashorn Wiki 来获取正式文档:

https://wiki.openjdk.java.net/display/Nashorn/Main

https://wiki.openjdk.java.net/display/Nashorn/Main

回答by Benjamin Winterberg

I played a lot with nashorn in the last couple of weeks. I wrote all my findings in an example-driven tutorial:

在过去的几周里,我和 nashorn 一起玩了很多。我在一个示例驱动的教程中写下了我所有的发现:

http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/

http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/

It covers the following topics:

它涵盖以下主题:

  • calling javascript functions from java code
  • calling java methods from javascript
  • using java classes from within javascript
  • summary of all language extensions (e.g. for each)
  • 从java代码调用javascript函数
  • 从javascript调用java方法
  • 在 javascript 中使用 java 类
  • 所有语言扩展的摘要(例如每个)

I hope it's helpful for you to start with Nashorn.

我希望从 Nashorn 开始对您有所帮助。

回答by pardeep131085

Nashorn is a JavaScript enginedeveloped in the Java programming language by Oracle. It is based on the (JSR 292) and has been released with Java 8. Oracle's JDK 8 or OpenJDK 8 include a command-line tool called jjs. It can be found in the bin/ folder of a JDK installation along with the well-known java, javac, or jar tools.

Nashorn 是Oracle 用 Ja​​va 编程语言开发的JavaScript 引擎。它基于 (JSR 292) 并随 Java 8 一起发布。Oracle 的 JDK 8 或 OpenJDK 8 包括一个名为 jjs 的命令行工具。它可以在 JDK 安装的 bin/ 文件夹中与众所周知的 java、javac 或 jar 工具一起找到。

Recently I worked on Oracle Nashornand compiled a tutorial on that. I hope that would be helpful

最近我在Oracle Nashorn 上工作并为此编写了一个教程。我希望这会有所帮助