Java Reference
In-Depth Information
Listing 12-4 contains a Nashorn script that creates two script objects and calls two
methods of a Java class, as shown in Listing 12-5. The script passes the script objects to
the Java methods. The Java methods print the properties of the passed objects and add
a new property to both script objects. The script prints the properties after the method
returns to confirm that the new properties added to script objects in Java code still exist.
Listing 12-4. A Nashorn Script That Calls Java Methods Passing Script Objects to Them
// scriptobjectprop.js
// Create an object
var point = {x: 10, y: 20};
// Create an array
var empIds = [101, 102];
// Get the Java type
var ScriptObjectProperties = Java.type("com.jdojo.script.ScriptObjectProp");
// Pass the object to Java
ScriptObjectProperties.propTest(point);
// Print all properties of the point object
print("In script, after calling the Java method propTest()...");
for(var prop in point) {
var value = point[prop];
print(prop + " = " + value);
}
// Pass the array object to Java
ScriptObjectProperties.arrayTest(empIds);
// Print all elements of teh empIds array
print("In script, after calling the Java method arrayTest()...");
for(var i = 0, len = empIds.length; i < len; i++) {
var value = empIds[i];
print("empIds[" + i + "] = " + value);
}
Listing 12-5. A Java Class Whose Methods Access Properties of Script Objects
// ScriptObjectProp.java
package com.jdojo.script;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Search WWH ::




Custom Search