开发者

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:

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜