views:

304

answers:

1

In Ruby I can add instance variables to a class by opening it, and doing something like this :


class Whatever
   def add_x
     @x = 20
   end
end

and this would add me an instance variable by the name of x. How can I do the same thing in Groovy?

+1  A: 

You can use Groovy's metaclass:

class Foo { String bar }
f = new Foo(bar:"one")
f.metaClass.spam = "two"
f.spam == "two" // returns true
f.spam = "eggs" // Change property value
f.spam == "eggs" //returns true
hohonuuli
NOTE: This only adds the variables to a particular instance of a class.
hohonuuli
TO add to all instances of use Foo.metaClass.spam = ""
hohonuuli