Calling Java Constructors with ColdFusion

I mentioned yesterday that Sam posted some great code that lets you upload files to ColdFusion without using CFFILE. His code can be shortened considerably with the use of the init() method:

<cfscript>
fileAsString = “”;
fileReader = createObject(“java”, “java.io.FileReader”);
fileReader.init(form.upFile);
bufferedReader = createObject(“java”, “java.io.BufferedReader”);
bufferedReader.init(fileReader);
try {
   do {
      fileAsString = bufferedReader.readLine();
      processLine(fileAsString);
   } while (true);
} catch (coldfusion.runtime.UndefinedVariableException e) {
// this indicates end of file, ok to ignore error
}
</cfscript>

Basically, you use the CreateObject() function to get a Java object. At that point, you can call static methods on the object or you can use the init() method to call the constructor of the Java object, which I’ve done above, ie:

// get a FileReader object
fileReader = createObject(“java”, “java.io.FileReader”);
// call the FileReader object constructor
fileReader.init(form.upFile);

If you’re curious about this kind of stuff, you should check out the article on Java, ColdFusion MX and Lucene integration I wrote for the July issue of ColdFusion Developer’s Journal, due to hit the stands anytime now.

One thought on “Calling Java Constructors with ColdFusion”

  1. i think the point of all that shilly shallying was the use of reflection to get around the no createobject restriction most shared hosts have in place.

Leave a Reply to PaulH Cancel reply

Your email address will not be published. Required fields are marked *