MethodSelectionException When Invoking Java From ColdFusion MX

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!

Comments

Thanks for the walkthrough,

Thanks for the walkthrough, very useful.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options