Over a million developers have joined DZone.

Adding Properties to Domain Classes Using Groovy

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

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

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= [:]
   def propertyMissing(String name, value) { dynamicProperties[name] = value }
   def propertyMissing(String name) { dynamicProperties= [name] }

2. Now extend Entity class from your domain class


class User extends Entity{
   String firstName
   String lastName


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.

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

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

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

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

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

{{ parent.tldr }}

{{ parent.urlSource.name }}