Groovy 属性迭代 [英] Groovy property iteration

查看:27
本文介绍了Groovy 属性迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的 Groovy 代码中,我替换了 Foo<实例的 feckarsedrink 属性的值/code> 与 Foo2

In the Groovy code below I replace the values of the feck, arse, drink properties of an instance of Foo with those of an instance of 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()


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

有没有更好的方法来做到这一点?我对上述代码的具体担忧是,属性名称以字符串形式存储在列表中,当(例如)使用重构 IDE 更改这些属性名称之一时,可能会遗漏这一点.

Is there a better way to do this? My specific concern with the code above is that the property names are stored as strings in a list, which would likely be missed when (for example) using a refactoring IDE to change one of these property names.

推荐答案

我还没有找到排除只读属性(即 metaClass、class)的好方法,但是如果要设置Foo 实例中的所有属性也在 Foo2 实例中,您可以执行以下操作.

I haven't yet found a good approach for excluding the read-only properties (i.e., metaClass, class), but if you want to set the value of all properties in the Foo instance that are also in the Foo2 instance you could do the following.

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"

这篇关于Groovy 属性迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆