Reputation: 25863
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
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