Sunday, April 19, 2009

ColdFusion: Small tip for using java objects

While searching the documentation the other day, I came across this small item that falls under the "I cannot believe I never knew that" category.

ColdFusion can automatically invoke getPropertyName() and setPropertyName(value) methods if a Java class conforms to the JavaBeans pattern. As a result, you can set or get the property by referencing it directly, without having to explicitly invoke a method.

In other words, in some cases you can just use myObject.propertyName instead of myObject.getPropertyName() or myObject.setPropertyName(). I do not know that I will use it just yet. But it is good to know, and might come in handy down the road ;)


Example using java.net.URL

<cfset urlString = "http://www.google.com/intl/en_ALL/images/logo.gif">
<cfset imageURL = createObject("java", "java.net.URL").init(urlString)>
<cfset img = createObject("java", "javax.imageio.ImageIO").read(imageURL)>
<cfdump var="#imageURL#" label="Methods of java.net.URL class"><br>

<b>Using Methods: getPropertyName</b><hr>
<cfoutput>
imageURL.getHost() = #imageURL.getHost()#<br>
imageURL.getPath() = #imageURL.getPath()#<br>
imageURL.getPort() = #imageURL.getPort()#<br>
imageURL.getProtocol() = #imageURL.getProtocol()#<br>
imageURL.getFile() = #imageURL.getFile()#<br>
</cfoutput>
<br><br>

<b>Using Properties: PropertyName</b><hr>
<cfoutput>
imageURL.Host = #imageURL.Host#<br>
imageURL.Path = #imageURL.Path#<br>
imageURL.Port = #imageURL.Port#<br>
imageURL.Protocol = #imageURL.Protocol#<br>
imageURL.File = #imageURL.File#<br>
</cfoutput>

2 comments:

Kurt Bonnet,  April 20, 2009 at 9:54 AM  

Wow, great find!!! Whenever I've done Java/CF hybrid apps I always used method calls, which is fine, but this is so much nicer. I never even thought that this was available. The syntax reminds me of how Groovy deals with properties.

cfSearching April 20, 2009 at 3:33 PM  

@Kurt,

Yes, it only works for getters and setters. But still a nice option!

- Leigh

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Header image adapted from atomicjeep