Passing a variable to be evaluated in groovy gstring

I am wondering if I can pass in a variable that will evaluate to String inside a gstring evaluation. The simplest example would be something like

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

I want to get the lastName value in the person instance. As a last resort, I can use reflection, but itโ€™s interesting that groovy should be something simpler, which I donโ€™t know about.

0
source share
1 answer

Can you try:

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

Instead of the first line in your example.

The Eval class is described here.

change

I guess (from your updated question) that you have a person variable, and then people pass the String string as person.lName , and you want to return the lName property of this class?

Can you try something like this with 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 ] } 
+3
source

Source: https://habr.com/ru/post/1395269/


All Articles