Passing variable to be evaluated in groovy gstring

时光毁灭记忆、已成空白 提交于 2019-11-29 16:29:38

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 ]
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!