Geo
Geo

Reputation: 96777

How can I add a field dynamically to a Java class using Groovy?

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?

Upvotes: 3

Views: 2283

Answers (1)

hohonuuli
hohonuuli

Reputation: 2014

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

Upvotes: 3

Related Questions