首页 > 解决方案 > 循环遍历类成员并在groovy中更新成员值

问题描述

我有一个关于循环遍历类成员和更新 groovy 中对象的成员值的问题:

class Test {    
    String a
    String b

    Test(String a, String b) {
        this.a = a
        this.b = b
    }

    String toString() {
        return "a is " + a + " b is " + b
    }

}

我想遍历对象成员并更新成员的值:

class Testing {
    static void main(String[] args) {
        Test test = new Test("hello", "world")
        test.properties.findAll {
            it.value.toString.equals('hello')
        }.each {
            it.setValue("new value")
        }
    }
}

我尝试将“hello”的值更改为“new value”,看起来它可以找到包含“hello”的成员,但之后的值相同it.setvalue(),如何正确更改对象中成员的值?

标签: groovy

解决方案


更改属性不会影响字段值更改。如果您想找到一个存储特定值的字段,例如hello,并将其更改为其他内容,那么您可以尝试使用在对象setProperty上调用的方法来执行此操作。test

考虑以下示例:

class Testing {
    static void main(String[] args) {
        Test test = new Test("hello", "world")

        test.properties.findAll {
            it.value == 'hello'
        }.each { field, _ ->
            test.setProperty(field as String, "new value")
        }

        println test
    }
}

输出:

a is new value b is world

推荐阅读