传递变量以在groovy gstring中进行评估

时间:2011-06-15 20:58:56

标签: groovy gstring

我想知道我是否可以将变量传递给gstring评估中的String进行评估。 最简单的例子就是

 def var ='person.lName'
 def value = "${var}"
 println(value)

我希望在person实例中输出lastName的值。作为最后的手段,我可​​以使用反射,但想知道在groovy中应该有一些更简单的东西,我不知道。

1 个答案:

答案 0 :(得分:3)

你可以尝试:

 def var = Eval.me( 'new Date()' )

代替示例中的第一行。

Eval class is documented here

修改

我猜测(根据您更新的问题)您有一个person变量,然后人们传递像person.lName这样的字符串,并且您想要返回该类的lName属性?

你能用GroovyShell尝试这样的东西吗?

// Assuming we have a Person class
class Person {
  String fName
  String lName
}

// And a variable 'person' stored in the binding of the script
person = new Person( fName:'tim', lName:'yates' )

// And given a command string to execute
def commandString = 'person.lName'

GroovyShell shell = new GroovyShell( binding )
def result = shell.evaluate( commandString )

或者,使用直接字符串解析和属性访问

// Assuming we have a Person class
class Person {
  String fName
  String lName
}

// And a variable 'person' stored in the binding of the script
person = new Person( fName:'tim', lName:'yates' )

// And given a command string to execute
def commandString = 'person.lName'

// Split the command string into a list based on '.', and inject starting with null
def result = commandString.split( /\./ ).inject( null ) { curr, prop ->
  // if curr is null, then return the property from the binding
  // Otherwise try to get the given property from the curr object
  curr?."$prop" ?: binding[ prop ]
}