Passing variable to be evaluated in groovy gstring
Asked Answered
G

1

2

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.

Gandy answered 15/6, 2011 at 20:58 Comment(0)
C
4

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 ]
}
Concede answered 15/6, 2011 at 21:7 Comment(4)
My bad I should have been little more specific, what I am trying to do is to pass the class instance and value of attribute dynamically. Some thing like obj.fName if I do var value = "${obj.fName}" evaluation is fine but if I do some thing like String str = "obj.fName" and I want to resolve value of fName at runtime. Reason being what attribute and object I will get at runtime is unknownGandy
Can you edit your question to put in an example of what you mean?Concede
@Gandy had another guess at what you are trying to do... I assume you have a 'person' object somewhere? Anyway, I hope I have shown you two possible methodsConcede
Thanks Tim, I tried the 2nd one and works exactly the way I wanted it to. Thanks a lot and appreciated your response.Gandy

© 2022 - 2024 — McMap. All rights reserved.