2016-07-05 80 views
1

我有一个.cfm文件用下面的代码:方法,ColdFusion的11,创建对象

<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

+2

这是一个很长的时间,因为我做的ColdFusion,但并不需要一个参数传递给'myObj.init() '以满足构造参数? –

+0

是的,你会,我没有参数也试过,没有运气。那主要是为了测试。 – theblindprophet

回答

1

我怀疑你正在运行到一个命名冲突。由于java源代码不包含名称,因此该类将成为默认包空间的一部分。如果不同的类(具有相同的名称)已被加载,则会导致问题。 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。

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

的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文件夹中。例如,使用上面的类,编译后的class文件应该被复制到:

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