2

我试图创建一个动态继承另一个类属性的域类构造函数。但我无法让它正常工作。

这是一个例子:

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.
  }
}
4

3 回答 3

2

你工作太辛苦了,复制一下属性:

class Example2 extends Example1 {

   String status

   Example2() {}

   Example2(Example1 orig) {
      this.properties = orig.properties
   }
}
于 2011-08-26T18:47:00.113 回答
1

经过足够的故障排除和在线搜索后,我找到了一个解决方案,以防万一有人在寻找类似的东西:

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

包括这个:

import org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass
于 2011-09-08T17:54:02.910 回答
0

我不完全清楚你想要完成什么,但有什么理由不能在“Example2”类中只有一个“Example1”字段?

于 2011-08-26T15:55:27.790 回答