Looping Over Java Arrays In ColdFusion
This is a really small blog post, but something that I've been truly appreciating as of late. Previously, I've blogged about ColdFusion 10 and the ability to loop over queries using the for-in syntax; but, one for-in update that I totally missed during the ColdFusion 10 launch was the ability to loop over Java arrays using the same simplified syntax.
To demonstrate, I'm grabbing a Java array of type "java.lang.Byte[]" and looping over it using the new ColdFusion 10 syntax:
<cfscript>
// Get the typed Java array - [java.lang.Byte].
bytes = javaCast( "string", "Funky Chicken!" ).getBytes();
for ( byte in bytes ) {
writeOutput( byte & ", " );
}
</cfscript>
In ColdFusion 10, when I run this code, I get the following output:
70, 117, 110, 107, 121, 32, 67, 104, 105, 99, 107, 101, 110, 33
Now, I know this might seem like a totally uninteresting post; but, if I tried to do the same thing in ColdFusion 9, I would get the following ColdFusion error:
You have attempted to dereference a scalar variable of type class [B as a structure with members.
Fortunately, looping of Java arrays in ColdFusion 9 (and earlier) is still fairly easy; you just need to use a standard index-loop instead of a for-in loop:
<cfscript>
// Get the typed Java array - [java.lang.Byte].
bytes = javaCast( "string", "Funky Chicken!" ).getBytes();
for ( i = 1 ; i <= arrayLen( bytes ) ; i++ ) {
writeOutput( bytes[ i ] & ", " );
}
</cfscript>
That's all. Minor, but super useful!
Want to use code from this post? Check out the license.
Reader Comments
The CF10 code doesn't run in Railo either because "No matching Method/Function for getBytes()".
Aint CFLive great :-)
What about this instead:
bytes = CharsetDecode('Funky Chicken!', 'utf-8');
@Steve, yup, that makes the code run on Railo (I suspect cflive.net has Java introspection disabled to ensure you can't create "dangerous" Java objects via sneaky means).