Adding properties to domain classes on the fly using groovy propertyMissing feature
Some times we need to add properties to domain classes on the fly.
Groovy supports propertyMissing for dealing with property resolution attempts. Steps to added dynamic properties to domain classes.
1. Create Entity.groovy class in src/groovy folder and use groovy propertyMissing feature in Entity class
class Entity { def dynamicProperties= [:] //setter def propertyMissing(String name, value) { dynamicProperties= [name] = value } //getter def propertyMissing(String name) { dynamicProperties= [name] } }
2. Now extend Entity class from your domain class
User.groovy>
class User extends Entity{ String firstName String lastName }Address.groovy
class Address extends Entity{ String country }
3. Testing the dynamic properties
class DynamicPropertyTester { static void main(String[] args) { User user = new User(); user.firstName = "Jagadeesh"; user.lastName = "Manne"; user.name = "$user.firstName $user.lastName"; //adding dynamic property "name" that doesnt exist in User domain println "Name : $user.name"; //out put //Name : Jagadeesh Manne Address address = new Address(); address.country = "India"; address.state = "AP"; //dynamic property address.city = "Vijayawada"; // dynamic property println "Country : $address.country, State : $address.state, City: $address.city" //out put // Country : India, State : AP, City: Vijayawada } }
Categories:
Groovy & Grails