The other day, I came across a cool little feature of ColdFusion that I was not aware of. Usually, when I go to create a Java object, I use the ColdFusion CreateObject() method and give it the Java class name that I want to create. I don't fully understand that magic that is CreateObject() and so, I assumed that you needed to call it for every single Java object that you wanted to create.
As it turns out, though, you only need to create the Java class once and then you can call the constructor method, Init(), on it as many times as you want. Check out this simple demo that utilizes one java.lang.StringBuffer class to create two StringBuffer instances:
<!--- Create a class of the Java string buffer. From this class, we are then going to instantiate new StringBuffer instances. ---> <cfset objStringBuffer = CreateObject( "java", "java.lang.StringBuffer" ) /> <!--- Create two string buffer objects by calling the constructor on the ONE StringBuffer class. ---> <cfset objBufferA = objStringBuffer.Init() /> <cfset objBufferB = objStringBuffer.Init() /> <!--- Add some text to string buffer A. ---> <cfset objBufferA.Append( "Put it in my A!" ) /> <!--- Add some text to string buffer B. ---> <cfset objBufferB.Append( "Put it in my B!" ) /> <!--- Output the two different string buffers. I do not expect them to be different, but I have never called Init() twice on the same object, so I am not sure how it will work. ---> <p> BufferA: #objBufferA.ToString()#<br /> BufferB: #objBufferB.ToString()# </p>
Running the above code, we get:
BufferA: Put it in my A!
BufferB: Put it in my B!
Each Init() call created a new StringBuffer instance that received it's own Append() data. How freakin' cool is that? I am sure those of you who are more Java-savvy are looking at that and thinking, "Well yeah - how else did you expect it work?" Yeah, well I don't know that stuff :) I guess the CreateObject() returns a class definition and then the Init() method is reflectively calling the "new" constructor on that class definition or something? It's all voodoo to me.
Want to use code from this post? Check out the license.