2

Im trying to create a Domain Class Constructor that inherits another class properties dynamically. But I cannot get it to work properly.

Heres an example:

class Example1 {

  String name;
  String location;
}

class Example2 extends Example1 {

  String status;

  public Example2 (Example1 orig){
    // Code here to set this.name and this.location  to name and location from orig
    // dynamically, so adding a field in Example1 does not require me to add that 
    // field here.
  }
}
Gregor
  • 133
  • 1
  • 7

3 Answers3

2

You're working too hard, just copy the properties:

class Example2 extends Example1 {

   String status

   Example2() {}

   Example2(Example1 orig) {
      this.properties = orig.properties
   }
}
Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
1

After enough troubleshooting and searching online I found a solution, here it is in case anyone is ever looking for something similar:

public Example2(Example1 orig){
   def d = new DefaultGrailsDomainClass(Example1.class)
   d.persistentProperties.each { val ->
       this[val.name] = orig[val.name]         
   }       
}

Include this:

import org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass
Gregor
  • 133
  • 1
  • 7
0

I'm not entirely clear on what it is that you want to accomplish, but is there any reason that you can't just have an "Example1" field in the "Example2" class?

Stephane Beniak
  • 181
  • 1
  • 1
  • 7
  • I did not want to duplicate data across multiple classes, sorta defeats the purpose of extending. I came up with a solution, it is posted above. – Gregor Aug 26 '11 at 15:59
  • or just make Example1 abstract (stick in src/groovy if Example1's props are all you need); extend Example2 from it and move on. – virtualeyes Aug 28 '11 at 01:39