Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy, get enclosing function's name?

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

like image 351
raffian Avatar asked Mar 02 '12 21:03

raffian


People also ask

How do you call a function in Groovy?

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.

How do you find the current method name?

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.

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]


1 Answers

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
like image 64
Robert Fey Avatar answered Nov 14 '22 00:11

Robert Fey