CF and Arrays of Basic Java Types (17/03/2004)
Today we've been struggling with what appears to be a limitation of ColdFusion - an inability to create arrays of basic java types (int, float etc). With all the supposed integration of CF and java, you'd think this was something that would be easily achievable, but apparently not...
The problem arose when trying to create a PDF document using iText. It looks a great package and everything was going well until we decided to use the
com.lowagie.text.pdf.PdfPTable class to get more control over a table. We were attempting the deceptively simple task of setting the column widths for a table.
In the PdfPTable class there's a method
setWidths(int widths), so the first thing to do was try creating a standard CF array and sending that. No joy - "The selected method setWidths was not found". After a bit of browsing we discovered that CF arrays are actualy instances of java the
java.util.Vector class, which provides a
toArray() method - yay! No, same result. Hmm. We tried using
javacast() and everything else we could think of, but nothing doing.
We managed to sort the problem in the end by going down to the java level itself and creating a new class and method to convert a ColdFusion array or numeric values to a java array of
int. Not really what I wanted to do, but needs must. If anyone else has any suggestions of a better way to do it, please let me know!
You can get the compiled java class file and the source file (if you're interested). To get this working you'll need to put the class file in your
[CFMXROOT]/wwwroot/WEB-INF/classes/ directory and restart the CF server. A usage example follows:
After the above mess of java classes to solve the problem of creating an array of java
int values, Sean Corfield helpfully pointed me towards a post by Christian Cantrell that shows how to create an empty byte array of a specific length.
It seems that
java.lang.reflect.Array is the saviour when it comes to creating arrays of basic java types in ColdFusion. So rather than using my custom java class, I can do the following instead:
For anyone using this method, remember that java arrays are zero-indexed (rather than CF arrays that are one-indexed).
Article Archive (September '03 – '05)
- Private CFC Methods and "this" 01/09/2003
- Active Sessions Across CF Applications 12/09/2003
- isnumeric() - Too Clever for It's Own Good? 15/03/2004
- Modifying Page Generated Content 15/03/2004
- CF and Arrays of Basic Java Types 17/03/2004
- Writing UTF-8 Text Files with ColdFusion 13/05/2004
- Top vs. Bottom Posting 09/07/2004
- Local (var) Scope Shortcut 27/12/2004
- Using Apache mod_headers to Change Downloaded Filenames 16/06/2005
- Changing the Working Directory of
- Flickr Workshop Review 29/09/2005