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

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


class Whatever
   def add_x
     @x = 20
   end
end

and this will add me an instance variable named x. How can I do the same in Groovy?

+3
source share
1 answer

You can use the Groovy 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
+3
source

Source: https://habr.com/ru/post/1714257/


All Articles