2016-07-05 79 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