How can I dynamically override the class "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 values โ€‹โ€‹of each () in a Java class.

I 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 does not 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?

+4
source share
1 answer

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

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

Leaving this type aside, I add a more general overloaded version of each () that takes an Object argument, rather than overriding the existing each () that takes a Closure argument.

+8
source

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


All Articles