3

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 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

NOTE: This only adds the variables to a particular instance of a class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.