找不到方法,Coldfusion 11,CreateObject

时间:2016-07-05 19:27:42

标签: java coldfusion coldfusion-11

我有一个.cfm文件,其中包含以下代码:

<cfset myObj=CreateObject( "java", "Test" )/>
<cfset a = myObj.init() >
<cfoutput>
    #a.hello()#
</cfoutput>
<cfset b = a.testJava() >

<cfoutput>
    #testJava()#
</cfoutput>

这引用了Java类文件:

public class Test
{
    private int x = 0;
    public Test(int x) {
            this.x = x;
    }
    public String testJava() {
            return "Hello Java!!";
    }
    public int hello() {
            return 5;
    }
}

我收到错误:

The hello method was not found.

Either there are no methods with the specified method name and argument types or the hello method is overloaded with argument types that ColdFusion cannot decipher reliably.
ColdFusion found 0 methods that match the provided arguments. If this is a Java object and you verified that the method exists, use the javacast function to reduce ambiguity.

我尝试了许多不同的方法,并且完全遵循了文档here.class文件 位于正确的位置,因为如果删除该文件,则会引发FNF错误。

我也试图以类似的方式使用cfobject标签而没有运气。没有找到任何方法。有什么想法吗?

Coldfusion 11,Hotfix 7

1 个答案:

答案 0 :(得分:1)

我怀疑你遇到了命名冲突。由于java源代码不包含package名称,因此该类成为默认包空间的一部分。如果已加载不同的类(具有相同名称),则可能会导致问题。 JVM无法知道您想要哪个“Test”类。

选择不同的(更独特的)类名应该可以解决问题。至少用于测试。但是,从长远来看,最好将类分组到包中以避免将来出现类似的命名冲突。

通常,自定义类捆绑到.jar files中以便于部署。见Java: Export to a .jar file in Eclipse。要在CF中加载jar文件,您可以:

  • 通过新的CF10 +应用程序设置this.javaSettings - 或 -
  • 动态加载它们
  • 将物理.jar文件放在CF类路径中的某个位置,例如{cf_web_root}/WEB-INF/lib。然后重新启动CF服务器,以便检测到新的jar。

<强>爪哇

package com.mycompany.widgets;
public class MyTestClass
{
    private int x;
    public MyTestClass(int x) {
            this.x = x;
    }
    public String testJava() {
            return "Hello Java!!";
    }
    public int hello() {
            return 5;
    }
}

<强> ColdFusion的:

 <cfset myObj = CreateObject( "java", "com.mycompany.widgets.MyTestClass" ).init( 5 ) />
 <cfdump var="#myObj#">

 <cfset resourcePath = "/"& replace(myObj.getClass().getName(), "." , "/")& ".class">
 <cfset resourceURL = getClass().getClassLoader().getResource( resourcePath )>

<cfoutput>
    <br>Resource path:  #resourcePath#
    <br>Resource URL <cfif !isNull(resourceURL)>#resourceURL.toString()#</cfif>
    <br>myObj.hello() = #myObj.hello()#
    <br>myObj.testJava() = #myObj.testJava()#
</cfoutput>

NB:虽然不是常态,但您可以从技术上将包与单个类文件一起使用。但是,您必须将整个包结构复制到WEB-INF\classes文件夹中。例如,使用上面的类,编译的类文件应该复制到:

 c:/{cfWebRoot}/web-inf/classes/com/mycompany/widgets/MyTestClass.class