Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Adding Properties to Domain Classes Using Groovy

DZone's Guide to

Adding Properties to Domain Classes Using Groovy

Sometimes we need to add properties to domain classes on the fly.

· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

Adding properties to domain classes on the fly using groovy propertyMissing feature

Sometimes 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
 
   }
   
}

I hope this article helps to create dynamic properties to domain clasess in groovy.


BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

Topics:
groovy ,high-perf ,grails ,performance ,grails development

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}