How to change methed behavior in groovy using this method in metaclass

I would like to "mess up" the plus method in Groovy as follows:

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

I get a StackOverflowException (which is not surprising).

Is there a way to use the "original" plus method inside a metaclass?

+5
source share
2 answers

The groovy idiomatic way is to keep a reference to the old method and call 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 is actually not well documented, and I planned to post a blog post about this exact topic today or tomorrow :).

+7
source

Use this for the spoil plus method:

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

Unsurprisingly, using the + operator in the overload plus method will result in StackOverflow; you need to use something other than the + operator.

Another mechanism: use XOR or some bit operator magic.

Regards, Peacefulfire

+1
source

Source: https://habr.com/ru/post/902880/


All Articles