October 01, 2003
Using Java Objects in ColdFusion
This is just a quick little code snippet for you ColdFusion users out there. With all of the hype of Java lately in the ColdFusion community, a lot of people have been taking the initiative to learn Java. However, it may not be obvious how you can apply your newfound knowledge of Java to ColdFusion development.
Below is a very simple code snippet of leveraging a built in Java class inside of a CFML template. Note that the color highlighting isn't quite right.. you'll be best copying and pasting this into Dreamweaver MX 2004 to view the code as it should be displayed.
<cfscript>
/* First, we create a Java object that references the built in
StringTokenizer class, available in the java.util package. This
line only declares the variable and its type, it does not call
the object's constructor.
It is similar to just doing the following in Java:
java.util.StringTokenizer stringTokenizer; */
stringTokenizer = createObject("Java", "java.util.StringTokenizer");
/* Next, we call the constructor. The way to do this in ColdFusion is
actually 2 part. If we call any non-static method of the object
the default constructor is implicity called. If you do not want to
call the default constructor, you can use the "init" method to have
ColdFusion call the object's constructor.
The code below is similar to doing the following in Java:
stringTokenizer = new java.util.StringTokenizer("This is my string", " ", false);
I won't explain the parameters.. they can be found here:
http://java.sun.com/j2se/1.4.1/docs/api/java/util/StringTokenizer.html
The java docs online should definitely be in your bookmark list. */
stringTokenizer.init("This is my string to break apart", " ", false);
/* Display the token count */
writeOutput("Tokens:" & stringTokenizer.countTokens() & "
");
/* Loop over the tokens... */
while (stringTokenizer.hasMoreTokens()) {
/* And display the token followed by a line break */
writeOutput(stringTokenizer.nextToken() & "
");
}
</cfscript>
It's that easy! Now you know how to start leveraging all of those built in Java classes that you've been using in your Java projects. Additionally, now you have an idea how to take advantage of Java classes that you can find all over the internet. Good luck!

Comments
Hey Darron-
I only wish I had taken the time to look further into this a long time ago. I have wasted SO MUCH time without the stringtokenizer. I'll be calling java classes all the time now. Thanks again- you rock!!!
Posted by: ultrafastneal at July 28, 2005 04:57 PM