Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically override a class's "each" method in Groovy?

Groovy adds each() and a number of other methods to java.lang.Object. I can't figure out how to use the Groovy metaclass to dynamically replace the default each() on a Java class.

I can see how to add new methods:

MyJavaClass.metaClass.myNewMethod = { closure -> /* custom logic */ }
new MyJavaClass().myNewMethod { item -> println item }  // runs custom logic

But it seems the same approach doesn't work when overriding methods:

MyJavaClass.metaClass.each = { closure -> /* custom logic */ }
new MyJavaClass().each { item -> println item }  // runs Object.each()

What am I doing wrong? How can I dynamically override each() in Groovy?

like image 723
rewbs Avatar asked Feb 28 '23 02:02

rewbs


1 Answers

Well I found the solution seconds after posting the question. I just needed to explicitly specify the type of the Closure argument on each():

MyJavaClass.metaClass.each = { Closure closure -> /* custom logic */ }
new MyJavaClass().each { item -> println item }  // runs custom logic

By leaving out the type, I was adding a more generic overloaded version of each() which accepts an Object argument, rather than overriding the existing each() which accepts a Closure argument.

like image 136
rewbs Avatar answered Mar 01 '23 14:03

rewbs