2012-02-13 51 views
0

我收到一个包含${somethingElse}的文本,但它只是一个普通的String。

我有一个类:

class Whatever { 

    def somethingElse = 5 

    void action(String sth) { 
     def test = [] 
     test.testing = sth 
     assert test.testing == 5 

    } 
} 

是否有可能使用Groovy?

编辑:

我的方案是:加载XML文件,其中包含有指向我的应用程序的一些其他值值的节点。所以我们假设我有shell.setVariable("current", myClass)。现在,在我的XML中,我希望能够将${current.someField}作为一个值。 麻烦的是,xml的值是一个字符串,我无法轻松评估它。 我无法预测用户如何创建这些“值”,我只是给他们使用少数类的能力。

当xml文件被加载时,我不能转换它,它必须是“按需”,因为我在特定情况下使用它,我希望它们能够在那个时刻使用值,而不是在什么时候加载xml文件。

任何提示?

回答

0

起初,我们所做的事情,使用这种格式的xml:

normalText#codeToExecuteOrEvaluate#normalText 

和使用replace封于正则表达式和groovyShell.evaluate()代码。 疯了。这花了很多时间和大量的记忆。

最后,我们改变了格式,以每串原来和装箱的脚本,我们希望能够评估:

Script script = shell.parse("\""+stringToParse+"\"") 

其中

stringToParse = "Hello world @ ${System.currentTimeMillis()}!!" 

然后我们能够调用script.run()尽可能多次,并且一切正常。 它实际上仍然如此。

2

有一两件事你可以做的是:

class Whatever { 

    def somethingElse = 5 

    void action(String sth) { 
    def result = new groovy.text.GStringTemplateEngine().with { 
     createTemplate(sth).make(this.properties).toString() 
    } 
    assert result == "Number 5" 
    } 
} 

// Pass it a String 
new Whatever().action('Number ${somethingElse}') 
+0

这看起来像很多开销!我们想过使用shell并设置绑定,但它看起来也是一种矫枉过正。 – Krystian 2012-02-13 10:15:03

+0

是的,我可以想到的另一种方式是使用'GroovyShell'并传递'Bindings' ...我想这种方式的优点是可以更好地控制允许的输入...''Eval.XXX'赢得了没有用,因为你不知道你将被要求的变量......--( – 2012-02-13 10:21:00