Piotr Kochański
Piotr Kochański

Reputation: 22672

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

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?

Upvotes: 5

Views: 1501

Answers (2)

Ted Naleid
Ted Naleid

Reputation: 26801

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

Upvotes: 7

Kartik Shah
Kartik Shah

Reputation: 932

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

Upvotes: 1

Related Questions