2

我想知道是否可以在 gstring 评估中传递要评估为 String 的变量。最简单的例子是这样的

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

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

4

1 回答 1

4

你能试一下吗:

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

代替您示例中的第一行。

Eval 类记录在这里

编辑

我猜测(根据您更新的问题)您有一个 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 ]
}
于 2011-06-15T21:07:03.140 回答