Groovy 有没有办法找出被调用方法的名称?
def myMethod() {
println "This method is called method " + methodName
}
这与鸭子类型相结合将允许非常简洁(并且可能难以阅读)的代码。
Groovy 支持通过以下方式拦截所有方法的能力invokeMethod
GroovyObject 的机制。
您可以覆盖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()
此外,您可以将此功能添加到现有类中:
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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)