2011-08-26 131 views
2

我試圖創建一個動態繼承其他類屬性的域類構造函數。但我無法讓它正常工作。從基類繼承Grails域類屬性

這裏有一個例子:

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. 
    } 
} 
+0

我試過了,說我必須要耐心等待8個小時:( – Gregor

+0

是的,有時間限制。也許明天回來吧:) –

回答

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 
0

我不是它是什麼,你要完成,但完全清楚沒有任何理由,你不能只在一個「例1」場「Example2」類?

+0

我不想跨多個班級複製數據,但是這種做法打敗了擴展的目的。我想出了一個解決方案,它在上面發佈。 – Gregor

+0

或者只是製作Example1摘要(如果Example1的道具都是你需要的,請粘貼在src/groovy中);從它擴展Example2並繼續。 – virtualeyes

2

你工作太辛苦了,剛纔複製的屬性:

class Example2 extends Example1 { 

    String status 

    Example2() {} 

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