Find out a method's name in Groovy

天大地大妈咪最大 提交于 2019-12-30 10:04:57

问题


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.


回答1:


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()



回答2:


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 the GroovyInterceptable interface).

class MyClass implements GroovyInterceptable {
    def invokeMethod(String name, args) {
        System.out.println("This method is called method $name")
        def metaMethod = metaClass.getMetaMethod(name, args)
        metaMethod.invoke(this, args)
    }

    def myMethod() {
        "Hi!"
    }
}

def instance = new MyClass()
instance.myMethod()

Also, you can add this functionality to an existing class:

Integer.metaClass.invokeMethod = { String name, args ->
    println("This method is called method $name")
    def metaMethod = delegate.metaClass.getMetaMethod(name, args)
    metaMethod.invoke(delegate, args)
}

1.toString()


来源:https://stackoverflow.com/questions/10103495/find-out-a-methods-name-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!