Replaced static method not replaced only when called from constructor

爱⌒轻易说出口 提交于 2019-12-24 00:38:18

问题


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

来源:https://stackoverflow.com/questions/36501291/replaced-static-method-not-replaced-only-when-called-from-constructor

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