Search code examples
javajavascriptjava-8nashorn

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


Oracle recently released Java 8, which includes Oracle Nashorn as a JavaScript engine. Does Nashorn only works one way in that you can convert JavaScript code into Java bytecode? Or is there any way to use it to convert Java code into JavaScript code?


Solution

  • The official page of the Project Nashorn says:

    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.

    So it's not the goal of the Nashorn projet to convert Java code to Javascript.

    You can use instead the GWT compiler wich does that.

    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.

    Beware that only a part of the Java Runtime Library can be emulated, you can find the list under this link.

    gwt-exporter is also a useful tool for your purpose.

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