Java Reference
In-Depth Information
turns a JavaScript reference to the Java type. In the following excerpt from the ex-
ample, the java.util.Date , java.util.ArrayList , and Employee classes
are made available to JavaScript using this technique.
var oldDate = Java.type("java.util.Date");
var array = Java.type("java.util.ArrayList");
var emp
= Java.type("org.java8recipes.chapter18.recipe18_06.Employee");
Once the types have been made available to JavaScript, they can be invoked in a
similar manner to their Java counterparts. For instance, new oldDate() is used to in-
stantiate a new instance of java.util.Date in the example. An important differen-
ce is that you don't use getters and setters to call upon Java properties. Rather, you
omit the “get” or “set” portion of the method and begin with a lowercase letter for the
field name. This makes property access from within JavaScript quite easy and much
more productive and readable. An example of such access can be seen from within the
forEach loop in the script. To access the employee hireDate property, simply call
employee.hireDate rather than employee.getHireDate() .
The ability to access Java seamlessly from within JavaScript makes it possible to
create seamless Java and JavaScript integrations.
18-7. Accessing Java Arrays and Collec-
tions in Nashorn
Problem
You need to gain access to a Java array or collection from within your Nashorn solu-
tion.
solution
Use the Java.type function to coerce Java arrays to JavaScript. Once coerced, you
instantiate the arrays by calling new and then accessing the members by specifying
their index by number. In the following example, a Java int array type is created
within JavaScript, and then it is instantiated and used for storage.
Search WWH ::




Custom Search