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!
Recent comments
2 weeks 4 days ago
5 weeks 1 day ago
6 weeks 5 days ago
6 weeks 6 days ago
7 weeks 6 days ago
9 weeks 5 days ago
9 weeks 6 days ago
10 weeks 1 day ago
10 weeks 5 days ago
10 weeks 5 days ago