代码之家  ›  专栏  ›  技术社区  ›  ratzip

在groovy中遍历类成员并更新成员值

  •  1
  • ratzip  · 技术社区  · 7 年前

    我有一个关于在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() ,如何正确更改对象中成员的值?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Szymon Stepniak    7 年前

    更改属性不会影响字段值的更改。如果要查找存储特定值的字段,如 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