Replaced static method not replaced only when call

2019-07-14 12:49发布

问题:

I have the following code

class ClassA {
    static String getA() {
        'A'
    }

    String string

    ClassA() {
        println getA()
        println ClassA.getA()
        string = getA()
    }
}


// Mocking
ClassA.metaClass.static.getA = { -> 'B' }
ClassA.metaClass.getA = { -> 'B' }
assert ClassA.getA() == 'B'

def test = new ClassA()
assert test.getA() == 'B'
assert test.string == 'B'

The last assertion

assert test.string == 'B'

does not pass. So what I understand is that getA() is not replaced only when called from constructor and with short name (not ClassA.getA() but only getA()).

Does anyone know why this happens and/or how to fix it?

EDIT: The method does return the correct value when used in field initialization String string = getA().