How to change behaviour of the method in groovy using that method in metaclass

点点圈 提交于 2020-01-02 04:48:29

问题


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?


回答1:


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 :).




回答2:


Use this to "spoil" plus method:

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

Not surprisingly, using '+' operator in overloading plus method will result in StackOverflow, it is required to use something other then '+' operator.

Other mechanism: Use XOR or some bit operator magic.

Regards, Peacefulfire



来源:https://stackoverflow.com/questions/920582/how-to-change-behaviour-of-the-method-in-groovy-using-that-method-in-metaclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!