In ColdFusion MX, you can create a Java object by calling the handy CreateObject() function.

<CFSET myObj = CreateObject("java", "java.util.Hashtable")>

Suppose you have the following Java class:

class Person {
    private String name;

    public void setName(String n) {
       this.name = n;
    }
}

Now, let’s create an instance in ColdFusion and set a name:

<CFSET somebodySpecial = CreateObject("java", "Person")>
<CFSET somebodySpecial.setName("Chuck")>

Cool, but what happens if you pass an argument that isn’t a string:

<CFSET somebodySpecial.setName(123)>
coldfusion.runtime.java.MethodSelectionException:
    The selected method setName was not found.

Whoops! ColdFusion wasn’t able to find a method of Person with a signature of “public void setName(int)“. What you need to do is cast the arguments to the correct datatype. For this example, you could do something like this:

<CFSET somebodySpecial.setName(ToString(123))>

The problem is what if you need to call methods that use other data types such as int, double, or boolean. ToString() won’t cut it. Instead use ColdFusion’s JavaCast() function:

JavaCast(type, variable)

type        "boolean"
            "int"
            "long"
            "float"
            "double"
            "String"

variable    A ColdFusion variable that holds a scalar or string type

So, the correct way is:

<CFSET somebodySpecial.setName(JavaCast("String", 123))>
<CFSET somebodySpecial.setName(JavaCast("String", "Chuck"))>

No more MethodSelectionExceptions!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Reddit

2 Comments »

  1. Thanks for the walkthrough, very useful.

    Comment by eve isk — August 27, 2008 @ 10:12 am

  2. What a best way to describe your view. Thanks for sharing with us. Really like your informative article. Hopefully we will get more interesting topic from you in future.thanks for this post – helped me understand this stuff better.
    After working on this stuff for a while longer, I’ve discovered that there is a cleaner means of achieving this same result.

    Here’s a (incomplete, hopefully clear) alternate approach to your sample program. The two keys are (1) that the comboBox redraws itself when the data provider is changed, and (2) the dataprovider will cast a E4X XML value to a XMLListCollection on assignment.

    Hope this helps (sure wish Adobe provided more extensive programming patterns for this)….

    Comment by war gold — October 15, 2008 @ 5:12 am

RSS feed for comments on this post. TrackBack URL

Leave a comment