Java 8 Nashorn JavaScript

Java 8 新特性Java 8 New Features


Nashorn is a JavaScript engine.

The Nashorn JavaScript Engine is no longer available in Java 15.

This has been marked as deprecated in Java 11:

@deprecated (forRemoval = true)

Starting from JDK 1.8, Nashorn replaced Rhino (JDK 1.6, JDK 1.7) as Java's embedded JavaScript engine. Nashorn fully supports the ECMAScript 5.1 specification as well as some extensions. It uses new language features based on JSR 292, including invokedynamic introduced in JDK 7, to compile JavaScript into Java bytecode.

Compared with the previous Rhino implementation, this brings a 2 to 10 times performance improvement.


jjs

jjs is a command-line tool based on the Nashorn engine. It accepts some JavaScript source code as parameters and executes that source code.

For example, we create a sample.js file with the following content:

print('Hello World!');

Open the console and enter the following command:

$ jjs sample.js

The output of the above program is:

Hello World!

jjs Interactive Programming

Open the console and enter the following command:

$ jjs
jjs> print("Hello, World!")
Hello, World!
jjs> quit()
>>

Passing Parameters

Open the console and enter the following command:

$ jjs -- a b c
jjs> print('字母: ' +arguments.join(", "))
字母: a, b, c
jjs> 

Calling JavaScript from Java

Using ScriptEngineManager, JavaScript code can be executed in Java, as shown in the following example:

Java8Tester.java file

import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; import javax.script.ScriptException; public class Java8Tester { public static void main(String args[]){ ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn"); String name = "Example"; Integer result = null; try { nashorn.eval("print('" + name + "')"); result = (Integer) nashorn.eval("10 + 2"); }catch(ScriptException e){ System.out.println("Error executing script:"+ e.getMessage()); } System.out.println(result.toString()); } }

Execute the above script, the output result is:

$ javac Java8Tester.java 
$ java Java8Tester
Example
12


Calling Java from JavaScript

The following example demonstrates how to reference Java classes in JavaScript:

var BigDecimal = Java.type('java.math.BigDecimal');

function calculate(amount, percentage) {

   var result = new BigDecimal(amount).multiply(
   new BigDecimal(percentage)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);
   
   return result.toPlainString();
}

var result = calculate(568000000000000000023,13.9);
print(result);

We use the jjs command to execute the above script, and the output is as follows:

$ jjs sample.js
78952000000000002017.94

Java 8 新特性Java 8 New Features

Other Extensions