如何在元类中使用该方法改变groovy中的方法的行为 [英] How to change behaviour of the methed in groovy using that method in metaclass
本文介绍了如何在元类中使用该方法改变groovy中的方法的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Integer.metaClass.plus {Integer.metaClass.plus {Integer.metaClass.plus} n - >委托+ n + 1}
断言2 + 2 == 5
我得到StackOverflowException (这并不奇怪)。
有没有什么方法可以在元类的闭包中使用原始加法?
解决方案
常规的惯用方法是保存对旧方法的引用并在新方法中调用它。
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
这实际上并没有很好的记录,我打算在今晚或明天发布关于这个确切主题的博客文章:)。 p>
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
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屋!
查看全文