Running JavaScript from Java using Java 8 Nashorn engine

java 8 nashorn

Nashorn engine

Java 6 introduced a JavaScript engine called Rhino that enabled embedding JavaScript code in Java.

In Java 8, a new JavaScript engine called Nashorn has been added that provides several new features.
 
To obtain Nashorn engine, we need to create an instance of ScriptEngineManager and then pass the engine name in getEngineByName() method as follows :


  // Get Nashorn engine instance
  ScriptEngineManager manager = new ScriptEngineManager();
  ScriptEngine engine = manager.getEngineByName("nashorn");

After getting the Nashorn engine, we can execute JavaScript code by using the engine’s eval() method.

 

Here are some examples of using the Nashorn engine to execute JavaScript code in Java.
 

Running inline JavaScript code from Java program

private static void executeInlineJS() {

  // Get Nashorn engine instance
  ScriptEngineManager manager = new ScriptEngineManager();
  ScriptEngine engine = manager.getEngineByName("nashorn");

  // Run inline script
  try {
    engine.eval("print('Hello Nashorn!');");
  } catch (ScriptException ex) {
    ex.printStackTrace();
  }
}

Output:

Hello Nashorn!
 

Running external JavaScript code from Java program

Lets create a JavaScript file hello.js with following code :


print("hello from external js file");

We can use the engine’s eval() method to execute the javascript code as shown in below example :

private static void executeExternalJS() {

  // Get Nashorn engine instance
  ScriptEngineManager manager = new ScriptEngineManager();
  ScriptEngine engine = manager.getEngineByName("nashorn");

  // Run external script
  try {
    engine.eval(new FileReader(
        "C:\\topjavatutorial\\hello.js"));
  } catch (ScriptException ex) {
    // This is the generic Exception subclass for the Scripting API
    ex.printStackTrace();
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  }
}

Output:

hello from external js file

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

1 Response

  1. Hi! We just released a framework for running Javascript in your Java projects using Nashorn. Check out http://purplejs.io. It’s Apache 2.0 licensed and free to use for everyone.

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: