Java Reference
In-Depth Information
There are three other global functions provided by jrunscript that are worth
mentioning. These functions can be used as functions and constructors:
jlist(javaList)
jmap(javaMap)
JSInvoker(object)
The jlist() function takes an instance of java.util.List and returns a JavaScript
object that you can use to access the List as if it is an array. You can use the bracket
notation with indexes to access the elements of the List . The returned object contains a
length property that gives you the size of the List . Listing 9-3 contains the code showing
how to use the jlist() function.
Listing 9-3. Using the jlist() Function
// jlisttest.js
// Create an ArrayList and add two elements to it
var ArrayList = Java.type("java.util.ArrayList");
var list = new ArrayList();
list.add("Ken");
list.add("Li");
// Convert the ArrayList into a Nashorn array
var names = jlist(list);
print("Accessing an ArrayList as a Nashorn array...");
for(var i = 0; i < names.length; i++) {
printf("names[%d] = %s", i, names[i]);
}
The following command executes the code in Listing 9-3 using the jrunscript
command-line shell:
C:\>jrunscript -f jlisttest.js
Accessing an ArrayList as a Nashorn array...
names[0] = Ken
names[1] = Li
The jmap() function takes an instance of java.util.Map and returns a JavaScript
object that you can use to access the Map . The keys in the Map becomes the properties
of the JavaScript object. Listing 9-4 contains the code showing how to use the jmap()
function.
 
Search WWH ::




Custom Search