在 Groovy 中有没有办法装饰每个类以添加跟踪? [英] In Groovy Is there a way to decorate every class to add tracing?
问题描述
我将如何在我的每个 groovy 类的每个方法调用中打印Entering ${methodname}",因为它进入方法调用?
How would I go about making every method call of every groovy class of mine print "Entering ${methodname}" as it enters the method call?
不必用 new TracingDecorator(new Object())
包装我创建的每个新对象?
Without having to wrap every new object I create with new TracingDecorator(new Object())
?
推荐答案
您需要覆盖所有类上的 metaClass.invokeMethod,并让它用您的跟踪内容包装对原始类的方法调用.
You'd need to override metaClass.invokeMethod on all of your classes and have it wrap the method call to the original class with your tracing stuff.
您可能会遍历从类加载器中获得的类列表,匹配某种命名/包模式,然后对每个类执行类似decorateMethodsWithLogging 的操作:
You could probably spin through the class list that you get from the classloader matching some sort of naming/package pattern and then for each of those do something like this decorateMethodsWithLogging:
class Foo {
def bar() {
println "in bar"
}
def baz(String name) {
println "in baz with $name"
}
}
def decorateMethodsWithLogging(clazz) {
def mc = clazz.metaClass
mc.invokeMethod = { String name, args ->
println "before $name, args = $args"
def result = mc.getMetaMethod(name, args).invoke(delegate, args)
println "after $name"
return result
}
}
decorateMethodsWithLogging(Foo.class)
def f = new Foo()
f.bar()
f.baz("qux")
这个打印
before bar, args = []
in bar
after bar
before baz, args = [qux]
in baz with qux
after baz
这篇关于在 Groovy 中有没有办法装饰每个类以添加跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!