Java Reference
In-Depth Information
Listing 9-4. Using the jmap() Function
// jmaptest.js
// Create an HashMap and add two elements to it
var HashMap = Java.type("java.util.HashMap");
var map = new HashMap();
map.put("Ken", "(999) 777-3331");
map.put("Li", "(888) 444-1111");
// Convert the HashMap into a Nashorn object
var phoneDir = jmap(map);
print("Accessing a HashMap as a Nashorn object...");
for(var prop in phoneDir) {
printf("phoneDir['%s'] = %s", prop, phoneDir[prop]);
}
// Use dot notation to access the proeprty
var kenPhone = phoneDir.Ken; // Same as phoneDir["Ken"]
printf("phoneDir.Ken = %s", kenPhone)
The following command executes the code in Listing 9-4 using the jrunscript
command-line shell:
C:\>jrunscript -f jmaptest.js
Accessing a HashMap as a Nashorn object...
phoneDir['Ken'] = (999) 777-3331
phoneDir['Li'] = (888) 444-1111
phoneDir.Ken = (999) 777-3331
The JSInvoker () function takes a delegate object as an argument. When a function
is invoked on the JSInvoker object, the invoke(name, args) method is called on the
delegate object. The name of the function being called is passed as the first argument to
the invoke() method; the passed argument to the function call is passed as the second
argument to the invoke() method. Listing 9-5 shows how to use the JSInvoker object.
Listing 9-5. Using the JSInvoker Object
// jsinvokertest.js
var calcDelegate = { invoke: function(name, args) {
if (args.length !== 2) {
throw new Error("Must pass 2 arguments to " + name);
}
var value = 0;
if (name === "add")
value = args[0] + args[1];
 
Search WWH ::




Custom Search