Groovy metaclass

青春壹個敷衍的年華 提交于 2019-12-24 17:07:48

问题


I have an existing class that extends a Number & implements Comparable, and I have been using this class extensively - including in my test classes (Junit & Spock). I have also been comparing instances of this class using == operator in the test classes.

As I understand it, Groovy will not use .equals() for comparison of classes which implements Comparable. Furthermore, after trawling Groovy code, I also found out that my class will be compared using Integer (hence losing decimal points, etc) - as it is not Floating point, BigDecimal, BigInteger, Long. i.e. Integer is the fallback.

To overcome this problem, I tried to do metaclass programming on Groovy's NumberMath class.

class Test2 {

    @Test
    void blah(){
        NumberMath.metaClass.static.compareTo = {  Number left, Number right ->
            println "982374"
            return 123
        }
        def num1 = new Decimal("9.01")
        def num2 = new Decimal("9.02")

        // this prints 982374
        println NumberMath.compareTo(num1, num2)

        // this doesnt print 982374
        num1 == num2
    }


}

But this doesnt seem to work (as shown in the snippet above). The == operator doesnt call the compareTo method which I have provided in the test. Have I missed something here?

Thanks in advance!

Regards,

Alex

来源:https://stackoverflow.com/questions/30046703/groovy-metaclass

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!