Program/ Example of Nashorn Javascript (js) Engine in Java 8 - call js function and pass java.util.Date and Employee object from java >
package nashorn1;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Date;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
class Employee {
String name;
public Employee(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee : name = " + name;
}
}
public class Nashorn_passDateAndObjectInJavascript {
public static void main(String[] args) throws Exception {
System.out.println("In java - START");
// Get nashorn engine
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// Pass the location of js file
engine.eval(new FileReader("E:/pocJmse/myNashornJavaScript.js"));
// NashornScriptEngine implements Invocable interface
Invocable invocable = (Invocable) engine;
System.out.println("\n"+"In java - 1 - Pass Date object to js");
// Invoke js (javascript) function - Pass Date object to js
invocable.invokeFunction("myFunction", new Date());
System.out.println("\n"+"In java - 2 - Pass Employee object to js");
// Invoke js (javascript) function - Pass Employee object to js
invocable.invokeFunction("myFunction", new Employee("Ankit"));
System.out.println("In java - FINISH");
}
}
/* OUTPUT
In java - START
In myNashornJavaScript.js
End myNashornJavaScript.js
In java - 1 - Pass Date object to js
In js function - Object type = [object java.util.Date]
In js function - print myObj = Sat Feb 18 20:11:27 IST 2017
In java - 2 - Pass Employee object to js
In js function - Object type = [object nashorn1.Employee]
In js function - print myObj = Employee : name = Ankit
In java - FINISH
*/
|
E:/pocJmse/myNashornJavaScript.js looks like this >
print('In myNashornJavaScript.js');
var myFunction = function(myObj) {
print("In js function - Object type = " + Object.prototype.toString.call(myObj));
print('In js function - print myObj = ' + myObj);
};
print('End myNashornJavaScript.js');
|
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.