Java Reference
In-Depth Information
= Java.type("org.java8recipes.chapter18.recipe18_06.Employee");
var empArray = new array();
var emp1 = new emp("Josh", "Juneau", new oldDate());
var emp2 = new emp("Joe", "Blow", new oldDate());
empArray.add(emp1);
empArray.add(emp2);
empArray.forEach(function(value, index, ar){
print("Employee: " + value);
print("Hire Date: " + value.hireDate);
});
Lastly, you execute the JavaScript file using a ScriptEngineManager :
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine nashorn = sem.getEngineByName("nashorn");
try {
nashorn.eval("load('/path-to/employeeFactory.js');");
} catch (ScriptException ex) {
Logger.getLogger(NashornInvoker.class.getName()).log(Level.SEVERE,
null, ex);
}
Here are the results:
Employee: Josh Juneau
Hire Date: Thu April 24 23:03:53 CDT 2014
Employee: Joe Blow
Hire Date: Fri April 25 12:00:00 CDT 2014
How It Works
It is very natural to use Java classes and libraries from within a Nashorn solution. The
example in this recipe demonstrates how to use a Java class that has been generated
specifically for use with a custom application, as well as how to use Java classes and
libraries that are part of Java SE. In order to make such classes available to JavaScript,
you must call the Java.type function from within the JavaScript and pass the string-
based fully qualified name of the Java class to be used. The Java.type function re-
Search WWH ::




Custom Search