Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at Scotch On The Rocks (SOTR) 2011 (Edinburgh) with:

Looping Over Java Arrays In ColdFusion

By Ben Nadel on
Tags: 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!

Tweet This Interesting post by @BenNadel - Looping Over Java Arrays In ColdFusion Thanks my man — you rock the party that rocks the body!



Reader Comments

The CF10 code doesn't run in Railo either because "No matching Method/Function for getBytes()".

Aint CFLive great :-)

Reply to this Comment

@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).

Reply to this Comment

Post A Comment

You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Oops!
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.