Java Proxy Component
I'm not sure if this is actually cool, or I just think it is, so I figured I would share.
I was working on demo code for tomorrow's presentation; one of things I wanted to show off was ColdFusion acting as an IM bot, running functionality in Java. To do that, I basically wanted to be able to dynamically call methods on the Java Math class. Basically, I want to type "pow 2 5" in the IM client and have it be the equivalent of "math.pow(2,5)".
Calling Java dynamically from ColdFusion isn't straightforward. But basically I figured if I could somehow use missing method to map calls to the underlying Java object then I could use cfinvoke to call the methods dynamically. The downside is that I couldn't figure out any way to call Java dynamically without resorting to evaluate:
<cfcomponent>
<cffunction name="init" access="public" output="false">
<cfargument name="path" type="string" required="true" />
<cfset variables.javaProxy = CreateObject("java", arguments.path) />
<cfreturn This />
</cffunction>
<cffunction access="public" name="onMissingMethod">
<cfargument name="missingMethodName" />
<cfargument name="missingMethodArguments" />
<cfset var attribute = "" />
<cfset var argumentList = "" />
<cfloop index="i" from="1" to="#ArrayLen(StructKeyArray(missingMethodArguments))#" >
<cfset argumentList = ListAppend(argumentList, missingMethodArguments[i]) />
</cfloop>
<cfreturn Evaluate("variables.javaProxy.#missingMethodName#(#argumentList#)") />
</cffunction>
</cfcomponent>
Once you have that CFC, you can call it this way:
<cfset math = CreateObject("component", "javaproxy").init("java.lang.Math") />
<cfset method = "pow" />
<cfinvoke component="#math#" method="#method#" returnvariable="result">
<cfinvokeargument name="1" value="2" />
<cfinvokeargument name="2" value="5" />
</cfinvoke>
<cfoutput>#result#</cfoutput>
Now, I'm sure I'll get trounced for the use of the dreaded "evaluate", but it definitely got the job done for me.
I think the cool thing is that once you have your Java object proxied to a CFC you can extend it. Not true Java object extension in CF, but not nothing.
3 responses so far ↓
1 Dave Shuck
I will go out on a limb and call it "cool" :)2 Raymond Camden
Ditto. Pretty neat. :)3 Henry Ho
Does this work?javaProxy[missingMethodName](argumentCollection=missingMethodArguments)
If not, you can still optimize your code by using ArrayToList() for your loop.
Leave a Comment