I'm trying to change the behaviour of the constructor of a groovy class by replacing a method in that class which is used to set a property but the properties are not getting set with the expected values.
class TestClass {
def noParam
def withParam
TestClass() {
noParam = noParam()
withParam = withParam('second test')
}
def noParam() {
return 'first test'
}
def withParam(param) {
return param
}
}
TestClass.metaClass.withParam = { param -> 'pass' }
TestClass.metaClass.noParam = {-> 'pass' }
def test = new TestClass()
assert test.withParam('dummy') == 'pass' //passes
assert test.withParam == 'pass' // fails
assert test.noParam() == 'pass' // passes
assert test.noParam == 'pass' // fails
Groovy is not using your metaclass overrides in the TestClass constructor when it executes the
noParam
andwithParam
methods. In fact, if you type the parameter in yourwithParam
method, the 2nd assert will also fail.Here's the output:
in the constructor: noParam = first test, withParam = second test
test.withParam
andtest.noParam
are actually callingtest.getWithParam()
andtest.getNoParam()
- they are returning the property values set in the constructor.test.withParam('dummy')
andtest.noParam()
are calling your metaclass method and returning "pass".As far as why groovy does not use the metaclass method in your constructor, I'm not sure... I couldn't find anything in the metaclass documentation...
Maybe you could use static methods instead?
Here's the output:
in the constructor: noParam = pass, withParam = pass