How can I dynamically override a classes "each" method?
Posted
by rewbs
on Stack Overflow
See other posts from Stack Overflow
or by rewbs
Published on 2010-05-02T16:06:58Z
Indexed on
2010/05/02
16:07 UTC
Read the original article
Hit count: 287
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?
© Stack Overflow or respective owner