2009-09-25 67 views
23

在Groovy代碼下面我與那些Foo2Groovy的財產迭代

class Foo { 
    def feck = "fe" 
    def arse = "ar" 
    def drink = "dr"  
} 

class Foo2 { 

    def feck = "fe2" 
    def arse = "ar2" 
    def drink = "dr2" 
} 


def f = new Foo() 
def f2 = new Foo2() 


["feck", "arse", "drink"].each {it -> 
    f."$it" = f2."$it" 
} 

實例的更換feckarsedrinkFoo實例的屬性的值是否有更好的方式來做到這一點?我對上述代碼的具體關注是,屬性名稱作爲字符串存儲在列表中,當(例如)使用重構IDE更改其中一個屬性名稱時,這些名稱可能會丟失。

+2

爲什麼不,「這將是一個普遍的問題」;)? – 2015-06-18 11:59:56

回答

27

我還沒有找到排除只讀屬性(即,metaClass,class)的好方法,但是如果您想要設置Foo實例中的所有屬性的值也在Foo2實例中你可以做到以下幾點。

class Foo { 
    def feck = "fe" 
    def arse = "ar" 
    def drink = "dr"  
} 

class Foo2 { 

    def feck = "fe2" 
    def arse = "ar2" 
    def drink = "dr2" 
} 


def f = new Foo() 
def f2 = new Foo2() 


f2.properties.each { prop, val -> 
    if(prop in ["metaClass","class"]) return 
    if(f.hasProperty(prop)) f[prop] = val 
} 

assert f.feck == "fe2" 
assert f.arse == "ar2" 
assert f.drink == "dr2" 
+0

可以請你幫我,如何檢查屬性類型? – Pushkar 2015-05-06 10:30:01

4

很晚了答案......但是怎麼樣採取只非合成declaredFieldsFoo類的。用你的方法:在重構例如一些變化Foo

class Foo { 
    def feck = "fe" 
    def arse = "ar" 
    def drink = "dr"  
} 

class Foo2 { 
    def feck = "fe2" 
    def arse = "ar2" 
    def drink = "dr2" 
} 


def f = new Foo() 
def f2 = new Foo2() 

Foo.declaredFields.findAll { !it.synthetic }*.name.each {it -> 
    f[it] = f2[it] 
} 

assert f.feck == "fe2" 
assert f.arse == "ar2" 
assert f.drink == "dr2" 

如果但不是在Foo2那麼Exception從這個代碼,告知什麼是錯的被拋出。