Groovy: Create class with dynamic properties

25 / Nov / 2009 by Himanshu Seth 1 comments

I recently came across a way in Groovy to define a class which can have dynamic getters and setters and properties can be added on the fly. The following code creates a class “MyExpandableClass” and defines two methods in the “getProperty and setProperty”. If we define these two methods in a groovy class, then calls to any getter or setter on objects of this class will go through these methods. Groovy also provide an Expando class which provides the same functionality.

class MyExpandableClass{
Map props=[:];
def getProperty(String property){
return props[property];
}
void setProperty(String property, Object newValue){
props[property] = newValue;
}
}
MyExpandableClass myExpandableObject = new MyExpandableClass()
myExpandableObject.numberValue=1234
myExpandableObject.dateValue=new Date()
myExpandableObject.stringValue="TEST"
println myExpandableObject.numberValue
println myExpandableObject.dateValue
println myExpandableObject.stringValue

In the above example, we can see that we can add any property to the object of “MyExpandableClass”. The properties that we add get stored in the map object in the class. We can think of our class as a simple wrapper around the map. Retrieving values from the object is same as calling getters for the class proeprties.

However, if we just have to use a dynamically expandable bean for storing data, then we can simply use groovy’s “Expando” class. Having our own implementation makes sense when we also want to add behaviour to this class.

This was my first taste of groovy’s metaprogramming powers. It truly is amazing.

Hope you find this useful.

Regards
~~Himanshu Seth~~

http://www.tothenew.com

FOUND THIS USEFUL? SHARE IT

comments (1 “Groovy: Create class with dynamic properties”)

Leave a Reply

Your email address will not be published. Required fields are marked *