groovy - 循环遍历类成员并在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()
,如何正确更改对象中成员的值?
解决方案
更改属性不会影响字段值更改。如果您想找到一个存储特定值的字段,例如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
推荐阅读
- c - 链表:按索引获取节点有意外结果
- reactjs - React Hook useEffect 缺少依赖项,在触发状态更改的按钮单击时运行条件
- python - RuntimeError('dot : 期望两个向量具有相同的 dtype,但发现 Double 和 Float
- elasticsearch - Composer 安装错误版本的 ElasticSearch
- c# - 解析异构 JSON 对象
- sql - 如何将 SCOPE_IDENTITY 作为值返回以在 Angular 应用程序中使用
- arrays - 使用 Flutter 中的类解析 JSON 文件
- c++ - 使用哪些数据类型从用户获取字符串,然后将其与数组中的其他字符串进行比较?
- reactjs - Heroku 应用程序给出“status=404”但没有出现
- python - 使用多标准加权对 Pandas DataFrame 进行排序