java - 未找到方法,Coldfusion 11,CreateObject

标签 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,修补程序 7

最佳答案

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

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

通常自定义类被捆绑到 .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。

Java

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;
    }
}

冷聚变:

 <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>

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

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

关于java - 未找到方法,Coldfusion 11,CreateObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38211189/

相关文章:

java - PHP 中的 3DES 与 Java 不同

Java用什么布局管理器把窗口分成两个区域

java - 使用 Java 进行搜索结果预览

javascript - angularjs 编写 ColdFusion 服务发送 json 数据和捕获的正确方法

coldfusion - 我们如何在 cfquery 结果中间添加一个新行?

java - Gradle 将缓存 8MB jar,但不会缓存 32MB jar

javascript - 尝试在页面加载时运行函数

coldfusion - 使用 Coldfusion cfswitch 标签失败?

coldfusion - 编码电子邮件地址 : EncodeForHTML or EncodeForURL