tags:

views:

242

answers:

1

Adobe ColdFusion is built on Java. Almost all simple variables in CFML/CFSCRIPT are java.lang.String until the operation needs it to be of a certain type.

I've always want to use startsWith() in String instead of the more bulky CFML variant.

left(str,4) EQ "test"

However, what's the general consensus of using underlying Java method in ColdFusion?

Would this be any safer to javacast() the var first?

javacast("String",x).startsWith("test");

What if the CF engine is not built on top of Java?

Thanks

+4  A: 

Yes, you can do this with Adobe ColdFusion and other CFML engines that are built on Java. It's actually simpler than you thought.

<cfset str = "hello what's up" />
#str.startsWith("hello")# <!--- returns "YES" --->
<cfif str.startsWith("h")>
  This text will be output
</cfif>

#str.startsWith("goodbye")# <!--- returns "NO" --->
<cfif str.startsWith("g")>
  This text will NOT be output
</cfif>

This is possible because CFML strings in ColdFusion are the same as Java strings. You can use any native string method (Java.lang.String) on a CFML string.

If you haven't guessed, this also works with CFML arrays (some kind of list, probably a java.util.Vector) and structs (probably a java.util.Map). Experiment with data types and the cfdump tag, you will find a lot of secrets.

One word of warning, this is not standard CFML, so if your underlying engine changes, including just upgrading to a new version, there are no guarantees that it will still work.

That said, string.startsWith() is native to Java as well as .NET, so this will also work if your CFML engine is BlueDragon.NET. The only CFML engines it will not work on are ColdFusion 5 and previous.

Is it safe to use? I would say yes. As long as CFML engines run on Java or .NET, it's perfectly safe. It's undocumented, but easy to understand, so I would say use it freely.

Nathan Strutz
I guess the question is.. How Safe?
Henry
I updated my response, last 3 paragraphs, to talk about if it's safe and my opinion if you should use it. If that doesn't answer it, please clarify your question.
Nathan Strutz
As Nathan says, it is all undocumented. So if you are not comfortable with the risk factor, using the documented javacast() function may be preferable. Though having said that, String's are a core part of both java and C#. So IMO, using the undocumented string.startsWith() would be far safer than depending on arrays being Vectors, for example. That I _could_ see changing in the near future.
Leigh