如何在元类中使用该方法更改Groovy中该方法的行为 [英] How to change behaviour of the method in groovy using that method in metaclass

查看:76
本文介绍了如何在元类中使用该方法更改Groovy中该方法的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过以下方式在Groovy中破坏"加法:

I would like to "spoil" plus method in Groovy in the following way:

Integer.metaClass.plus {Integer n -> delegate + n + 1}
assert 2+2 == 5

我得到StackOverflowException(这并不奇怪).

I am getting StackOverflowException (which is not surprising).

有什么方法可以在元类的闭包中使用原始"加法吗?

Is there any way to use "original" plus method inside metaclass' closure?

推荐答案

惯用的习惯做法是保存对旧方法的引用,并在新方法中调用它.

The groovy idiomatic way is to save a reference to the old method and invoke it inside the new one.

def oldPlus = Integer.metaClass.getMetaMethod("plus", [Integer] as Class[])

Integer.metaClass.plus = { Integer n ->
    return oldPlus.invoke(oldPlus.invoke(delegate, n), 1)        
}

assert 5 == 2 + 2

这实际上并没有得到很好的记录,我打算今晚或明天就此确切主题撰写一篇博客文章:).

This isn't actually that well documented and I was planning on putting up a blog post about this exact topic either tonight or tomorrow :).

这篇关于如何在元类中使用该方法更改Groovy中该方法的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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