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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With