Nashorn: JavaScript Engine for Java SE 8

In java 6, scripting engine was introduced. It was based on Mozilla Rhino. The idea was to enable programmer to use JavaScript in their java code.

In java 8, a new scripting engine was introduced that was developed by Oracle and named Nashorn. It allows the programmer to code in JavaScript rather than java using the dynamic coding capabilities that language support. It is completely new engine and it replaces the old Rhino engine.

How can you use Nashorn
Nashorn can be used from the command line or within your java code.

Nashorn From command line
You can use Nashorn from the command line. For that first open your command prompt. To get to the Nashorn language you have to type its command that is “jjs”. It will get you to the Nashorn language.

Nashorn: JavaScript Engine for Java SE 8

Now here you can write JavaScript code and press enter and it will execute. For the sake of example let us create a variable named “a” and initialize it with a string and then print it.
Nashorn: JavaScript Engine for Java SE 8

Note:
One important thing to note is that here we are working in purely javaScript Engine and we are not in browser environment which means we don’t have access to the objects that are part of Document Object Model of browser world. It is a pure JavaScript language detached from browser However because at the back end you are working in java that means you can use java classes in your code. To use the class, you have to give fully qualified name of the class.

In following example we create a variable named nums and initialize it with a stack which is java class. Then we push some values and print it. For sake of example we pop a value and then again print it.

Nashorn: JavaScript Engine for Java SE 8

Nashorn within Java Code

You can also use your javaScript code in your java program with the help Nashorn Engine. You can write complete block of code in javaScript and you can execute them using scriptEngine.

Example
To use the ScriptEngine for Nashorn, First you have to declare a variable of ScriptEngineManager. It has access to all the ScriptEngines built into java runtime.

ScriptEngineManager manager = new ScriptEngineManager();
Now you can get the ScriptEngine using the manager. ScriptEngine is a interface and you can initialize it with number of methods that manager provides. The best way is to use the method named “getEngineByName” and for the argument type “nashorn”. Be sure to spell right.
ScriptEngine engine = manager.getEngineByName("nashorn");
The next step is to create the script in a string. It can be any javaScript code.
String script = "var welcome = 'Hello '"
				+ "welcome += 'World'"
				+ "welcome";
Now you can execute this script using eval function of engine and it will give the result back in the form of object and you can type cast it if you know what is you getting back. In our case it is String.
String result = (String) engine.eval(script);
System.out.println(result);
Nashorn: JavaScript Engine for Java SE 8
Executing Script in Separate File
As we executed the script from a String, we can also execute the script that is in other file.

Example
For external script we have “readurl.js” that has following code in it. This code gets rss feed from knowledgeAspire.com.
var feed = 'http://feeds.feedburner.com/KnowledgeAspire';
var url = new java.net.URL(feed);
input = new java.util.Scanner(url.openStream());
input.useDelimiter('$');
var contents = input.next();
contents;
Here we have main method that executes this script.
public static void main(String[] args) {
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("nashorn");
		
		File f = new File("scripts/readurl.js");
		try {
			Object result;
			Reader reader = new FileReader(f);
			result = engine.eval(reader);
			System.out.println(result);
		} catch (FileNotFoundException e) {
			System.out.println("file does not exist...");
			e.printStackTrace();
		} catch (ScriptException e) {
			System.out.println("JavaScript Error...");
			e.printStackTrace();
		}
	}
The idea is same, we create a scriptEngine from manager then use reader to read the script and feed that reader to the eval function of engine. Then Nashorn will execute the javaScript code and written the result.
Tags: Java Nashorn
comments powered by Disqus