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

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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.


Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

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

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}