Java Reference
In-Depth Information
// At this point, trg has the property named u, but src does not.
printf("trg-3: x=%d, y=%d,z=%d, u=%d", trg.x, trg.y, trg.z, trg.u);
printf("src-3: x=%d, y=%d,z=%d, u=%s", src.x, src.y, src.z, src.u);
// Now add a new property to src
src.v = 30;
// Contrary to our expectation, trg.v does not exist. It may indicate a bug.
printf("trg-4: x=%d, y=%d,z=%d, u=%d, v=%s", trg.x, trg.y, trg.z, trg.u,
trg.v);
printf("src-4: x=%d, y=%d,z=%d, u=%s, v=%d", src.x, src.y, src.z, src.u,
src.v);
trg-1: x=100, y=200,z=300
trg-2: x=100, y=200,z=30
src-2: x=100, y=200,z=30
trg-3: x=100, y=200,z=30, u=30
src-3: x=100, y=200,z=30, u=undefined
trg-4: x=100, y=200,z=30, u=30, v=undefined
src-4: x=100, y=200,z=30, u=undefined, v=30
There are two practical uses of the Object.bindProperties() method:
To enumerate the properties of Java objects inside Nashorn
scripts
You can import an object's properties into global scope as if those
properties are declared globally
You cannot enumerate the properties of Java objects using the for..in or for..
each..in statements in Nashorn. Notice that we are talking about Java objects, not
Nashorn objects. The solution is to bind the properties of Java objects to a Nashorn object
and use one of these iteration statements on the Nashorn object. Listing 4-15 shows how
to iterate over the properties of java.util.HashSet object.
Listing 4-15. Iterating Over Properties of Java Objects
// bindjavaobject.js
var trg = {};
var src = new java.util.HashSet();
// Try iterating src properties
print("Iterating over src properties:");
for (var propName in src) {
print(propName); // Will not get here
}
 
Search WWH ::




Custom Search