Java Script Nashorn

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java Nashorn

Nashorn is a JavaScript engine. It is used to execute JavaScript code dynamically at JVM (Java Virtual Machine). Java provides a command-line tool jjs which is used to execute JavaScript code.

You can execute JavaScript code by using jjs command-line tool and by embedding into Java source code.


Example: Executing by Using Terminal

Following is the step by step process to execute JavaScript code at the JVM.

1) Create a file hello.js.

2) Write and save the following code into the file.

  1. var hello = function(){  

  2.     print("Hello Nashorn");  

  3. };  

  4. hello();  

3) Open terminal

4) Write command jjs hello.js and press enter.

After executing command, you will see the below output.

Output:

Hello Nashorn

Example: Executing JavaScript file in Java Code

You can execute JavaScript file directly from your Java file. In the following code, we are reading a file hello.js with the help of FileReader class.

  1. import javax.script.*;  
  2. import java.io.*;  
  3. public class NashornExample {  
  4.     public static void main(String[] args) throws Exception{  
  5.         // Creating script engine  
  6.         ScriptEngine ee = new ScriptEngineManager().getEngineByName("Nashorn");  
  7.         // Reading Nashorn file  
  8.         ee.eval(new FileReader("js/hello.js"));  
  9.     }  
  10. }  

Output:

Hello Nashorn

Example: Embedding JavaScript Code in Java Source File

You can embed your JavaScript code in Java source file. Java compiler will not complaint but it is not good practice when you have large source code. In the following example, we are evaluating JavaScript code.

  1. import javax.script.*;  
  2. public class NashornExample {  
  3.     public static void main(String[] args) throws Exception{  
  4.         // Creating script engine  
  5.         ScriptEngine ee = new ScriptEngineManager().getEngineByName("Nashorn");  
  6.         // Evaluating Nashorn code  
  7.         ee.eval("print('Hello Nashorn');");  
  8.     }  
  9. }  

Output:

Hello Nashorn

Example: Embedding JavaScript Expression

You can embed JavaScript expressions and variables in JavaScript code. In the following code we are embedding a variable to string. To execute this program you need to pass a flag -scripting in command-line.

File: hello.js

 
  1. var hello = function(msg){  
  2.     print("Hello ${msg}");  
  3. };  
  4. hello("Nashron");  

Command: jjs -scripting hello.js

Output:

Hello Nashorn

Heredocs

In Nashorn, heredocs are simply multi-line strings. You can create it with << followed by a special termination marker, which is EOF. You can also embed JavaScript expressions in ${...} expressions.


Example : Heredocs in JavaScript File

file: hello.js

  1. var message = <<EOF  
  2. This is a java script file  
  3. it contains multiple lines  
  4. of code.  
  5. let's execute.  
  6. EOF  
  7. print(message)  

Command: jjs -scripting hello.js

Output:

This is a java script file
it contains multiple lines
of code.
let's execute.

Example: Setting JavaScript variable in Java File

You can pass value to JavaScript variable in the Java file. In the followed example, we are binding and passing variable to JavaScript file.

File: hello.js

  1. print("Hello "+name);  

File: NashornExample.java

  1. import javax.script.*;  
  2. import java.io.*;  
  3. public class NashornExample {  
  4.     public static void main(String[] args) throws Exception{  
  5.         // Creating script engine  
  6.         ScriptEngine ee = new ScriptEngineManager().getEngineByName("Nashorn");  
  7.         //Binding script and Define scope of script  
  8.         Bindings bind = ee.getBindings(ScriptContext.ENGINE_SCOPE);  
  9.         bind.put("name""Nashorn");  
  10.         // Reading Nashorn file  
  11.         ee.eval(new FileReader("js/hello.js"));  
  12.     }  
  13. }  

Output:

Hello Nashorn

Import Java Package in JavaScript File

Java provides a facility to import Java package inside the JavaScript code. Here, we are using two approaches to import Java packages.


Example1: Import Java Package in JavaScript File

File: hello.js

  1. print(java.lang.Math.sqrt(4));  

Output:

2

Example2: Import Java Package in JavaScript File

File: hello.js

 
  1. var importFile = new JavaImporter(java.util);  
  2. var a = new importFile.ArrayList();  
  3. a.add(12);  
  4. a.add(20);  
  5. print(a);  
  6. print(a.getClass());  

Output:

[12, 20]
class java.util.ArrayList

Example3: Import Java Package in JavaScript File

you can import multiple packages at the same time.

File: hello.js

 
  1. var importIt = new JavaImporter(java.lang.String,java.util,java.io);  
  2. with (importIt) {  
  3.   var linkedHS = new LinkedHashSet();  
  4.   linkedHS.add(new File("abc"));  
  5.   linkedHS.add(new File("hello.js"));  
  6.   linkedHS.add("india".toUpperCase());  
  7. }  
  8. print(linkedHS);  

Output:

[abc, hello.js, INDIA]

Calling JavaScript function inside Java code

You can call JavaScript function inside the Java file. In the followed example, we are calling JavaScript functions.


Example: Calling function inside Java code

File: hello.js

 
  1. var functionDemo1 = function(){  
  2.     print("This is JavaScript function");  
  3. }  
  4. var functionDemo2 = function(message){  
  5.     print("Hello "+message);  
  6. }  

File: NashornExample.java

 
  1. import javax.script.*;  
  2. import java.io.*;  
  3. public class NashornExample {  
  4.     public static void main(String[] args) throws Exception{  
  5.         // Creating script engine  
  6.         ScriptEngine ee = new ScriptEngineManager().getEngineByName("Nashorn");  
  7.         // Reading Nashorn file  
  8.         ee.eval(new FileReader("js/hello.js"));  
  9.         Invocable invocable = (Invocable)ee;  
  10.         // calling a function  
  11.         invocable.invokeFunction("functionDemo1");  
  12.         // calling a function and passing variable as well.  
  13.         invocable.invokeFunction("functionDemo2","Nashorn");       
  14.     }  
  15. }  

Output:

This is JavaScript function
Hello Nashorn