m0skit0
m0skit0

Reputation: 25863

Cannot replace static method

I'm trying to replace a static method at runtime using MetaClass.

class MyClass {
    private static String getString() {
        'Hello'
    }

    String testString

    MyClass() {
        testString = getString()
    }
}

MyClass.metaClass.static.getString = { ->
    'Hello world!'
}

def test = new MyClass()
assert test.testString == 'Hello world!'

However this it doesn't work.

Caught: Assertion failed: 

assert test.testString == 'Hello world!'
       |    |          |
       |    Hello      false
       MyClass@5876a9af

Upvotes: 0

Views: 689

Answers (1)

CptBartender
CptBartender

Reputation: 1220

Due to a bug in Groovy 2.4.3, it is not possible to change private methods via metaclass. I've changed the method to public (well, default) and also changed the constructor so that it explicitly calls it's class' getString method and now it seems to be working in Groovy web console

Full code after edits:

class MyClass {
    static String getString() {
        'Hello'
    }
    String testString
    MyClass() {
        testString = MyClass.getString()
    }
}
MyClass.metaClass.static.getString = {'Hello world!'}
def test = new MyClass()
assert test.testString == 'Hello world!'

Upvotes: 3

Related Questions