2011-06-15 93 views
0

我想知道如果我可以传递变量作为字符串评估gstring里面评估。 简单的例子会像传递变量在groovy gstring

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

我希望得到的输出lastName的价值在人的情况下一些东西。作为最后的手段,我可​​以使用反思,但不知道在常规中应该有一些简单的事情,我不知道。

回答

3

你可以尝试:

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

代替你的榜样的第一线。

Eval class is documented here

编辑

我猜(从您更新的问题),你有一个人变量,然后人们传递一个字符串像person.lName,你想退回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 ] 
} 
+0

我的坏我本来应该更具体一点,我试图做的是动态传递属性的类实例和值。有些东西,如 obj.f名称 如果我做 var value =“$ {obj.fName}”评价是好的,但如果我做一些像 String str =“obj.fName”,我想解析fName的值在运行时。原因是什么属性和对象,我会在运行时得到的是不知道 – Amit 2011-06-15 21:17:58

+0

你可以编辑你的问题,把你的意思吗? – 2011-06-15 21:45:19

+0

更新的例子实际上是我想要做的。 – Amit 2011-06-16 01:27:51