开发者

How Does "Use" work in groovy?

Hi I have the following Code Snippet;

class StringCalci
{
        static def plus(Integer self, Integer Operand)
        {
                return self.toInteger() * Operand.toInteger()
        }
}
use (StringCalci)
{
        println("inside the Use method!")
        println( 12 + 3 )
}
println(12+3)

I was been shocked to see the use of Use in groovy. The thing is this I can add methods to the Class at run-time(my own methods).when I was looking at the above code, I was Thinking how does Groovy make things possible like this! The use of println inside the Use is multiplying the two given numbers(because I have Override the plus method) , where as the outsi开发者_运维技巧de println adds it! My question is how does Groovy recognise the println executes in Use and println outside the Use. Is Use is a keyword/method? I need to understand behind the scenes of this process.. Please let me know :) Thanks in Advance :)


Welcome to the wonderful world of dynamic languages where everything is possible and nothing is certain!

This feature is called Categories. As for the implementation:

  • use is in fact not a keyword but a method which the Groovy runtime adds to the Object class, which makes it available everywhere.
  • I think the functionality is implemented mainly in the class GroovyCategorySupport
  • Judging from the Javadoc, it's based on keeping a map of overriden methods in a ThreadLocal which is then consulted for every method call.
  • yeah, that's not so great for performance, but so are pretty much all the dynamic "magic" features that Groovy and similar languages offer (and there's lots of them).
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜