2012-02-13 53 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