adding methods to singular objects in groovy

In both Python and Ruby you can add methods just to an object ( instead of all instances of a class ). The great thing is, you can do the same in Groovy. Here’s how :

def a = new File(".")
a.metaClass.bla = {
    println File.separator;
a.bla() // this will print \ or / , depending on your operating system

bla isn’t a suggestive name, I’m sure you agree. But, this illustrates the point. If for example, you instantiate a second object, and try to call the same method on it, like in the following example:

def b = new File("..")
b.bla() // this will throw a MissingMethodException

You can notice that the second object does not share the bla method.

I’m sure you guys can put this to good use !


0 Responses to “adding methods to singular objects in groovy”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog Stats

  • 238,127 hits

%d bloggers like this: