Java 8 Nashorn JavaScript
Nashorn a javascript engine.
JDK 1.8 from the beginning, Nashorn substituted Rhino (JDK 1.6, JDK1.7) became Java embedded JavaScript engine. Nashorn fully supports ECMAScript 5.1 specification and some extensions. It is based on the use of the new language features JSR 292, which contains introduced in JDK 7 in invokedynamic, the JavaScript compiled into Java byte code.
Compared with the previous Rhino realization, which brought 2-10 times the performance.
jjs
jjs Nashorn engine is based command-line tool. It accepts some of JavaScript source code for the parameters, and executes the source code.
For example, we create sample.js file with the following contents:
print('Hello World!');
Open the console, enter the following command:
$ jjs sample.js
The above program output is:
Hello World!
jjs interactive programming
Open the console, enter the following command:
$ jjs jjs> print("Hello, World!") Hello, World! jjs> quit() >>
Passing parameters
Open the console, enter the following command:
$ jjs -- a b c jjs> print('字母: ' +arguments.join(", ")) 字母: a, b, c jjs>
Java calling JavaScript
Use ScriptEngineManager, JavaScript code can be executed in Java, the examples are as follows:
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 = "w3big"; Integer result = null; try { nashorn.eval("print('" + name + "')"); result = (Integer) nashorn.eval("10 + 2"); }catch(ScriptException e){ System.out.println("执行脚本错误: "+ e.getMessage()); } System.out.println(result.toString()); } }
Implementation of the above script, output is:
$ javac Java8Tester.java $ java Java8Tester w3big 12
JavaScript Calling Java
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 jjs command script above, the output results are as follows:
$ jjs sample.js 78952000000000002017.94