开发者

Inherit Grails Domain Class properties from a base Class

开发者 https://www.devze.com 2023-03-31 14:31 出处:网络
Im trying to create a Domain Class Constructor that inherits another class properties dynamically. But I cannot get it to work properly.

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 开发者_JAVA技巧a field in Example1 does not require me to add that 
    // field here.
  }
}


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

class Example2 extends Example1 {

   String status

   Example2() {}

   Example2(Example1 orig) {
      this.properties = orig.properties
   }
}


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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消