[Java] - The Nashorn Engine
Monday, February 19, 2018
Note: Oracle Nashorn Engine be able to SE 9.
I. It's just javascript.
Example 1:
------------helloWorld.js------------
//start
var hello = function() {
print("Hello Oracle Nashorn Engine");
};
helloworld();
//end
------------helloWorld.js------------
Evaluating it as simple as this:
$jjs helloWorld.js
Hello Oracle Nashorn Engine
Example 2:
------------helloWorld.js------------
//start
var sum = function (a, b) {
return a + b;
};
print("Sum = " + sum(3,4));
//end
------------helloWorld.js------------
Evaluating it as simple as this:
$jjs helloWorld.js
Sum = 7
II. Embedding Oracle Nashorn
Oracle Nashorn from a Java application to define javascript statements, call it as we write code in a javascript file. It helps when we want to load a javascript code to Oracle Nashorn and work on that.
Example:
package learning.javacore.oraclenashsorn.samples;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Sample1 {
private static final String NASHORN_ENGINE = "nashorn";
public static void main(String[] args) {
//declared ScriptEngineManager and ScriptEngine
ScriptEngineManager engineMrg = new ScriptEngineManager();
ScriptEngine engine = engineMrg.getEngineByName(NASHORN_ENGINE);
//declared a js codes.
String js = "var sum = function(a,b) { return a + b;};";
try {
engine.eval(js);
System.out.println(engine.eval("sum(3,4);"));
} catch (ScriptException e) {
}
}
}
We can do more with Oracle Nashorn. Please see details: http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html
Bài liên quan
Comments[ 0 ]
Post a Comment