使用两个不同的setter在Groovy中设置属性值

时间:2014-04-14 21:56:09

标签: groovy

我想允许用户使用BigDecimalBigDecimal在我的班级中设置String属性(出于向后兼容性原因)。

extension.timeoutFactor = 1.81
extension.timeoutFactor = "2.12"

尝试使用两个具有不同参数类型的setter:

class PitestPluginExtension {
    BigDecimal timeoutFactor

    void setTimeoutFactor(BigDecimal timeoutFactor) {
        this.timeoutFactor = timeoutFactor
    }

    @Deprecated
    void setTimeoutFactor(String timeoutFactor) {
        //display deprecation warning
        this.timeoutFactor = timeoutFactor.toBigDecimal()
    }
}

但是Groovy失败了:

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object
    '2.12' with class 'java.lang.String' to class 'java.math.BigDecimal'

如果直接调用setter,一切正常,但这是一个Gradle plugin,人们习惯使用属性赋值。

是否可以告诉Groovy(1.8.6)在属性赋值中使用不同的输入类型(最好不使用Groovy元编程)?

2 个答案:

答案 0 :(得分:2)

import java.math.*

class PitestPluginExtension {
    private BigDecimal timeoutFactor

    void setTimeoutFactor(timeoutFactor) {
        this.timeoutFactor = new BigDecimal(timeoutFactor)
    }

    def getTimeoutFactor() {
        this.timeoutFactor
    }
}

// ignore differences due to precision errors
void compareImprecisely(BigDecimal expected, BigDecimal actual) {
    BigDecimal roundedExpected = Math.round(expected * 100) / 100
    BigDecimal roundedActual = Math.round(actual * 100) / 100
    assert roundedExpected == roundedActual
}

def ppe = new PitestPluginExtension()

def expected = new BigDecimal('1.11')

// test assigning a string
ppe.timeoutFactor = '1.11'
compareImprecisely expected, ppe.timeoutFactor

// test assigning a BigDecimal
ppe.timeoutFactor = 1.11
compareImprecisely expected, ppe.timeoutFactor

答案 1 :(得分:0)

以下解决方案(由@ Don的答案暗示!)似乎有效,因为1.21 BigDecimal无损地转换为String并在设置器中使用。之后它可以得到BigDecimal

class PitestPluginExtension {
    BigDecimal timeoutFactor

    void setTimeoutFactor(String timeoutFactor) {
        this.timeoutFactor = new BigDecimal(timeoutFactor)
    }
}

def extension = new PitestPluginExtension()
extension.timeoutFactor = "1.81"
assert extension.timeoutFactor == 1.81
extension.timeoutFactor = 1.21
assert extension.timeoutFactor == 1.21