I encounter the following problem today when using Groovy closure with class inheritance involved:
The base class “BaseClass” has a protected method “doA”, in which it has a method invocation which takes a closure as argument. In that closure, a private method “doB” of “BaseClass” is used. This class works fine;
Now a subclass of “BaseClass” is created as “SubClass”, it overrides “doA”. After some operations, it invokes “doA” in “BaseClass” as well. But at this moment, an “MissingMethodException” is thrown which complains “doB” cannot be found.
The following code works:
1 | class NerdHandler { |
But the following code gets “MissingMethodException: No signature of method: SubClass.doB() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl) values: [Say hello to nerd!]“:
1 | class NerdHandler { |
However if you change the “private” to “protected” in line “19”(private void doB(String statement)), it works.
Someone else also reports this issue here and here.
From this error, it seems a Groovy closure’s context is not the class which defines it, but the one which triggers its invocation.