gpt4 book ai didi

groovy - 传递变量以groovy gstring进行评估

转载 作者:行者123 更新时间:2023-12-02 15:49:48 25 4
gpt4 key购买 nike

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

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

我正在寻找在人实例中输出lastName的值。作为最后的选择,我可以使用反射,但是想知道在groovy中应该有一些更简单的事情,我不知道。

最佳答案

你能试一下吗:

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

代替示例中的第一行。

Eval class is documented here

编辑

我在猜测(从您更新的问题中)您有一个person变量,然后人们传入了像 person.lName这样的String,并且您想返回该类的 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 ]
}

关于groovy - 传递变量以groovy gstring进行评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41292744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com