Groovy metaclass

I have an existing class that extends number and implements Comparable, and I use this class extensively - including in my test classes (Junit and Spock). I have also compared instances of this class using the == operator in test classes.

As I understand it, Groovy won't use .equals () to compare classes that implement Comparable. Also, after trashing Groovy code, I also found out that my class will be compared using Integer (hence losing decimal points, etc.) - since it is not a floating point, BigDecimal, BigInteger, Long. that is, Integer is reserved.

To solve this problem, I tried to do metaclass programming in the Groovy 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 that doesn't seem to work (as shown in the snippet above). The == operator does not call the compareTo method that I provided in the test. Am I missing something here?

Thanks in advance!

Hello,

Alex

+1


source to share





All Articles