Find out a method's name in Groovy

后端 未结 2 1742
一向
一向 2021-01-13 19:18

Is there a way in Groovy to find out the name of the called method?

def myMethod() {
    println \"This method is called method \" + methodName
}
         


        
2条回答
  •  花落未央
    2021-01-13 20:02

    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:

    import static org.codehaus.groovy.runtime.StackTraceUtils.sanitize
    
    def myMethod() {
      def name = sanitize( new Exception().fillInStackTrace() ).stackTrace.find {
        !( it.className ==~ /^java_.*|^org.codehaus.*/ )
      }?.methodName
    
      println "In method $name"
    }
    
    myMethod()
    

提交回复
热议问题