I'm using Groovy 1.8.4, trying to get the name of the enclosing function...
def myFunction() {
println functionName??
}
I've tried delegate
, this
, owner
, Groovy complains no such objects found.
I also tried the Java hack new Exception().getStackTrace()[0].getMethodName()
, but that just prints newInstance0
In Groovy, we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () . This can be especially useful in for example a DSL written with Groovy.
The current method name that contains the execution point that is represented by the current stack trace element is provided by the java. lang. StackTraceElement. getMethodName() method.
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
import org.codehaus.groovy.runtime.StackTraceUtils
def getCurrentMethodName(){
def marker = new Throwable()
return StackTraceUtils.sanitize(marker).stackTrace[1].methodName
}
def helloFun(){
println( getCurrentMethodName() )
}
helloFun()
output:
helloFun
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With