Coldfusion handling Java null's
I have been reading a number of posts how to handle nulls in Coldfusion. Coldfusion doesnt naturally handle a "null" object returned from Java (as far as I can see, I have read a few posts and still no definate answer, so here goes for a couple of tips, just to keep myself sane and to remind myself.
There are two ways that you can handle a null and it depends what the returned object is, firstly lets handle nulls where the returned object might be something simple like a number or a string, the easiest method would be to simplify the variable, so you can trim the result, if it is null, you will get an empty string:
<cfset myString = CreateObject("java", "com.some.Class").init().getName()>
<cfif Len(myString)>
#myString#
</cfif>
The second method is used if you return complex data, such as an Array, Structure or Java Objects themselves:
<cfset UsersArray = CreateObject("java", "com.some.Class").init().getUsers()>
<cfif isDefined("UsersArray")>
<cfdump var="#UsersArray#">
</cfif>
If someone has a better method of managing returned nulls from Java, please let me know and I can update this post.
Tags: coldfusion · reference · webdev
9 responses so far ↓
1 Justin Wilson // Sep 22, 2008 at 4:10 PM
<cfset vector = CreateObject("java", "java.util.Vector")>
<cfset vector.setSize(1)>
<cfreturn vector.get(0) />
</cffunction>
I found this technigue, can be very usefull!
2 Kurt Wiersma // Sep 22, 2008 at 4:11 PM
3 Mark Drew // Sep 22, 2008 at 4:11 PM
4 Vince Bonfanti // Sep 22, 2008 at 4:11 PM
You might be interested to know that we recently announced that BlueDragon 7.0 will include both support for "null" as a keyword in CFML expressions and an isNull() function. I demonstrated these during one of my presentations at CFUNITED, and will put more info up on my blog in the next week or two.
5 Mark Drew // Sep 22, 2008 at 4:11 PM
6 Damon Cooper // Sep 22, 2008 at 4:11 PM
This really makes life easier when working with Java methods from CFML.
For example
x = CreateObject("java", "test.Hello");
x.init();
ret = x.sayHello(JavaCast("null", ""));
There's obviously a lot more to working with with nulls, but this was a quick little feature we added in CF7 that addresses the most commonly reported annoyance by folks working with Java and CFML together.
Feedback welcome!
Damon
7 Mark Drew // Sep 22, 2008 at 4:12 PM
8 Matthew giles // Sep 22, 2008 at 4:12 PM
9 Cliff // Sep 22, 2008 at 4:13 PM
e.g.
<cfif arguments.V eq "">
<cfset a = ws.BP( P: arguments.P, V: arguments.V )>
<cfelse>
<cfset a = ws.BP( P: arguments.P, V: JavaCast( "null", "" ) )>
</cfif>
Leave a Comment