pch*_*onz 4 reflection groovy introspection
在Groovy中有没有办法找出被调用方法的名称?
def myMethod() {
println "This method is called method " + methodName
}
Run Code Online (Sandbox Code Playgroud)
这与鸭子打字相结合将允许非常简洁(并且可能难以阅读)的代码.
Groovy支持通过invokeMethodGroovyObject机制拦截所有方法的能力.
您可以覆盖invokeMethod哪些将基本上拦截所有方法调用(为了拦截对现有方法的调用,该类还必须实现该GroovyInterceptable接口).
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()
Run Code Online (Sandbox Code Playgroud)
此外,您可以将此功能添加到现有类:
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()
Run Code Online (Sandbox Code Playgroud)