Groovy模糊方法重载

时间:2015-10-29 09:13:47

标签: groovy

早上好 - 我看到类似的问题已被问过几次,但它们似乎都是针对已编译的项目或涉及Gradle的项目。无论如何,我收到了错误

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

我无法解决问题所在。据我所知,所有方法都正确完成,没有歧义。谁能指出我出错的地方?

2 个答案:

答案 0 :(得分:10)

模糊的方法调用是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。因此,请确保不要将空值传递给BigDecimal的构造函数。

答案 1 :(得分: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)