开发者

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

开发者 https://www.devze.com 2022-12-29 02:17 出处:网络
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.

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:

开发者_如何学JAVA
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消