Find out a method's name in Groovy

后端 未结 2 1776
一向
一向 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:03

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

提交回复
热议问题