Is there a way in Groovy to find out the name of the called method?
def myMethod() {
println "This method is called method " + methodName
}
This, in combination with duck typing would allow for quite concise (and probably hard to read) code.
No, as with Java there's no native way of doing this.
You could write an AST transform so that you could annotate the method and this could set a local variable inside the method.
Or you can do it the good old Java way of generating a stackTrace, and finding the correct StackTraceElement with something like:
Groovy supports the ability to intercept all methods through the
invokeMethod
mechanism of GroovyObject.You can override
invokeMethod
which will essentially intercept all method calls (to intercept calls to existing methods, the class additionally has to implement theGroovyInterceptable
interface).Also, you can add this functionality to an existing class: