Passing variable to be evaluated in groovy gstring

2019-01-29 03:55发布

问题:

I am wondering if I can pass variable to be evaluated as String inside gstring evaluation. simplest example will be some thing like

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

I am looking to get output the value of lastName in the person instance. As a last resort I can use reflection, but wondering there should be some thing simpler in groovy, that I am not aware of.

回答1:

Can you try:

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

In place of the first line in your example.

The Eval class is documented here

edit

I am guessing (from your updated question) that you have a person variable, and then people are passing in a String like person.lName , and you want to return the lName property of that class?

Can you try something like this using 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 )

Or this, using direct string parsing and property access

// 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 ]
}