在Groovy中有没有一种方法来装饰每个类来添加跟踪? [英] In Groovy Is there a way to decorate every class to add tracing?

查看:88
本文介绍了在Groovy中有没有一种方法来装饰每个类来添加跟踪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会如何在进入方法调用时使每个常规类的每个方法调用打印输入$ {methodname}?



使用新的TracingDecorator(new Object())?创建每个新创建的对象?

解决方案

您需要在所有类上重写metaClass.invokeMethod,并使用跟踪内容将方法调用包装到原始类中。



你可以从classloader中得到类名单,匹配某种命名/包模式,然后为每个人做这样的decorateMethodsWithLogging:



<$ p $





$ b $(b
$) b $ b printlnin baz with $ name

}



def decorateMethodsWithLogging(clazz){
def mc = clazz.metaClass

mc.i nvokeMethod = {String name,args - >
println在$ name之后,args = $ args
def result = mc.getMetaMethod(name,args).invoke(delegate,args)
println$ name后
返回结果



$ b decorateMethodsWithLogging(Foo.class)

def f = new Foo()
f.bar()
f.baz(qux)

p>

 在bar之前,args = [] 
在bar
在bar之后
在baz之前,args = [qux]
in baz with qux
baz


How would I go about making every method call of every groovy class of mine print "Entering ${methodname}" as it enters the method call?

Without having to wrap every new object I create with new TracingDecorator(new Object())?

解决方案

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.

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

this prints

before bar, args = []
in bar
after bar
before baz, args = [qux]
in baz with qux
after baz

这篇关于在Groovy中有没有一种方法来装饰每个类来添加跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆