Java Reference
In-Depth Information
and utilized in the same manner as the Java type would be used from within Java code.
The examples in this recipe demonstrate how to access Java arrays, ArrayLists ,
and HashMaps from within JavaScript.
When working with a Java array type from JavaScript, the type of array must be
passed to the Java.type() function, including an empty set of brackets. Once the
type has been obtained and assigned to a JavaScript variable, it can be instantiated by
including the static size of the array within brackets, just as an array would be instanti-
ated in the Java language. Similarly, the array can be accessed by specifying indices to
assign and retrieve values from the array. To go backward and pass a JavaScript array
to Java, use the Java.to() function, passing the JavaScript array to its Java-type
counterpart. In the following code, a JavaScript string array is coerced into a Java type.
jjs> var strArr = ["one","two","three"]
jjs> var javaStrArr = Java.type("java.lang.String[]");
jjs> var javaArray = Java.to(strArr, javaStrArr);
jjs> javaArray[1];
two
jjs> javaArray.class
class [Ljava.lang.String;
Collections are very similar to arrays, in that the Java.type() function must be
used to obtain the Java type and assign it to a JavaScript variable. The variable is then
instantiated and the Collection type is then accessed in the same manner as it
would be in the Java language.
18-8. Implementing Java Interfaces
Problem
You want to make use of a Java interface from your Nashorn solution.
Solution
Create a new instance of the interface, passing a JavaScript object consisting of proper-
ties. The JavaScript object properties will implement the methods defined in the inter-
face. In the following example, an interface used for declaring employee position types
Search WWH ::




Custom Search