本文介绍了groovy:有一个字段名称,需要设置值并且不想使用switch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个字段的对象

I have an object with several fields,

class TestObj { 
  def field1
  def field2
}

我有一对值v1 ="field1"和v2 ="value2",我想根据v1的名称将v2设置为适当的字段,但我不想使用switch或if语句,我一直认为除了做这样的事情之外,必须有一种更时髦"的方法来获得结果:

I have a pair of values v1="field1" and v2="value2" I would like to set v2 into the appropriate field based on the name of v1, but I'd prefer not to have to do it with a switch or if statements, I keep thinking there has to be a much "groovier" way of achieving the result other than doing something like this:

setValues(def fieldName, def fieldVal) {
  if (fieldName.equals("field1")) {
    field1 = fieldVal
  }
  if (fieldName.equals("field2")) {
    field2 = fieldVal
  }
}

我尝试这样做:

setValues(def fieldName, def fieldVal) {
  this['${fieldName}'] = fieldVal
}

但是失败了,说没有属性$ {fieldName}

However that fails, saying there's no property ${fieldName}

谢谢.

推荐答案

在获取字段时可以使用GString,例如:

You can use GStrings when you get a field, like this:

def obj = new TestObj()
def fieldToUpdate = 'field1'
obj."$fieldToUpdate" = 3

这篇关于groovy:有一个字段名称,需要设置值并且不想使用switch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 10:23