是否可以使用 Nashorn 将 Java 代码转换为 Java 脚本?

Is it possible to use Nashorn to convert Java code to Javascript?

Oracle 最近发布了 Java 8,其中包括作为 JavaScript 引擎的 Oracle Nashorn。 Nashorn 是否只能以一种方式工作,您可以将 Java 脚本代码转换为 Java 字节码?或者有什么方法可以用它把Java代码转换成Java脚本代码?

Project Nashorn 的官方页面说:

Nashorn's goal is to implement a lightweight high-performance JavaScript runtime in Java with a native JVM. This Project intends to enable Java developers embedding of JavaScript in Java applications via JSR-223 and to develop free standing JavaScript applications using the jrunscript command-line tool.

因此,将 Java 代码转换为 Java 脚本并不是 Nashorn 项目的目标。

您可以使用 GWT compiler 来代替。

The GWT SDK provides a set of core Java APIs and Widgets. These allow you to write AJAX applications in Java and then compile the source to highly optimized JavaScript that runs across all browsers, including mobile browsers for Android and the iPhone.

请注意,只有一部分 Java Runtime Library 可以被模拟,你可以在这个 link.

下找到列表

gwt-exporter 也是一个有用的工具。

Develop an application or library in GWT and use gwtexporter annotations to make classes and methods available from javascript.