2015-10-29 434 views
6

早上所有 - 我發現類似的問題已經被問了幾次,但它們似乎都是針對已編譯的項目或涉及Gradle的項目。無論如何,我發現了錯誤Groovy含糊不清的方法重載

Caused by: javax.script.ScriptException: groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method java.math.BigDecimal#<init>. 
Cannot resolve which method to invoke for [null] due to overlapping prototypes between: 
[class [C] 
[class java.lang.String] 
當我運行這個腳本

String amt = "1" 
String currency = "GBP" 
String targetCurrency = "USD" 

def settlement = crossCurrencyClient.crossCurrency(amt, currency, targetCurrency) 

return transfer.amount * new java.math.BigDecimal (settlement) 

本身觸發此

import groovyx.net.http.HTTPBuilder 
import groovyx.net.http.RESTClient 
import groovy.json.JsonBuilder 
import groovy.json.JsonOutput 
import static groovyx.net.http.Method.GET 
import static groovyx.net.http.ContentType.JSON 

public class CrossCurrencyClient { 

    def issuingAddress = "rBycsjqxD8RVZP5zrrndiVtJwht7Z457A8" 
    String source = "rUR5QVHqFxRa8TSQawc1M6jKj7BvKzbHek" 
    String multiplier = "" 
    def resURL = "http://url-string.com/v1/" 
    def resourceIdClient = new RESTClient("${resURL}") 

    public String generateUUID() { 
     def resourceId = resourceIdClient.get(path:"uuid").data.uuid 
     println "resourceId = " + resourceId 
     return resourceId 
     } 

    public String crossCurrency(String amt,String currency,String targetCurrency) { 

     def http = new HTTPBuilder("${resURL}accounts/${source}/payments/paths/${source}/${amt}+${targetCurrency}+${issuingAddress}?source_currencies=${currency}+${issuingAddress}" 
) 

     http.request(GET,JSON) { 

      response.success = { resp, json -> 
       if(json.success){ 
        multiplier = json?.source_amount?.value 
       } 
      } 

      response.failure = { resp -> 
       println "Request failed with status ${resp.status} and message : ${resp.message}" 
       return "Something went wrong" 
      } 
     } 
    return multiplier  
    } 
} 

CrossCurrencyClient crossCurrencyClient = new CrossCurrencyClient() 

我想不通的問題是在這裏什麼。據我所見,所有的方法都做得很好,沒有歧義。任何人都可以指出我要去哪裏?

+0

由於BigDecimal有幾個構造函數我假設我無法解決哪一個需要,因此錯誤 –

回答

6

模糊方法調用是BigDecimal的構造函數:

Ambiguous method overloading for method java.math.BigDecimal#<init> 

再說一個可能的過載是BigDecimal(String val)的構造函數。我不確定[class [C]是指什麼,但我想它是指BigDecimal(BigInteger val)

這導致了它的線大概是這樣的一個:

new java.math.BigDecimal (settlement) 

因爲結算變量爲空。在類似的情況下,你可以只投這樣的參數:

new java.math.BigDecimal (settlement as String) 

但它可能會在稍後拋出NullPointerException。所以只要確保你不會將null傳遞給BigDecimal的構造函數。

+0

謝謝,明白了。正如你正確地建議的那樣,它拋出一個NullPointerException,但這很容易理清。 – Horsebrass

0

正如例外說的那樣,settlementnull所以Groovy不知道調用BigInteger的哪個構造函數(因爲null可能是)。

正是由於空:

  if(json.success){ 
       multiplier = json?.source_amount?.value 
      } 

所以如果jsonsource_amount爲空,那麼multiplier爲空,所以你返回null ...

您可以停止你的方法返回null。 ..或更改構造函數爲:

return transfer.amount * new BigDecimal((String)settlement)