Saturday, January 12, 2008

Creating a Multi-Dimensional Java Array from ColdFusion

I recently needed to create a multi-dimensional byte array from ColdFusion and pass it to a java class. I was unable to use javacast("byte[]", ...) because the code needed to be compatible with MX7. Initially, I constructed the array manually, using an old tip from Christian Cantrell's blog.


<cfscript>
// cfSearching: create a 3 x 20 byte array
byteClass = createObject("java", "java.lang.Byte").TYPE;
reflectArray = createObject("java","java.lang.reflect.Array");
arr1 = reflectArray.newInstance(byteClass, javacast("int", 20));
arr2 = reflectArray.newInstance(byteClass, javacast("int", 20));
arr3 = reflectArray.newInstance(byteClass, javacast("int", 20));
multiArray = arrayNew(1);
arrayAppend(multiArray, arr1);
arrayAppend(multiArray, arr2);
arrayAppend(multiArray, arr3);
// cfSearching: pass the array to the java object
myJavaObject.grabBytes(multiArray);
</cfscript>


This struck me as bit awkward, so I reviewed the API and realized there is a simpler way. The java.lang.reflect.Array class contains a second newInstance() method which accepts an int[] array of dimensions. So my final code was reduced to:


<cfscript>
byteClass = createObject("java", "java.lang.Byte").TYPE;
reflectArray = createObject("java","java.lang.reflect.Array");
arrayDimensions = listToArray("3,20");
multiArray = reflectArray.newInstance(byteClass, arrayDimensions);
myJavaObject.grabBytes(multiArray);
</cfscript>


I just thought I would post this tip in case it helps someone.

2 comments:

Unknown August 28, 2009 at 3:02 AM  

I'm trying to do something similar to this, except with a multidimensional integer array.
I can see how your code works on the coldfusion side of things but what type did you use for the parameter in your grabBytes()java method?

Thanks in advance,
Odhran.

cfSearching August 28, 2009 at 1:09 PM  

@Odhran,

With a 3-d array it was probably something like:

public static void someMethod(byte[][][] arr) {
...
}

Same concept for a 3-d int array:

public static void someMethod(int[][][] arr) {
...
}


-Leigh

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Header image adapted from atomicjeep