问题描述
我想从数据库中读取一个字符串,并通过将其转换为GString来替换占位符.我可以用Eval做到这一点吗?还有其他想法吗?
I want to read a String from database and replace the placeholder by converting it to a GString. Can I do this with Eval? Any other ideas?
String stringFromDatabase = 'Hello ${name}!'
String name = 'world'
assert 'Hello world!'== TODO
推荐答案
您可以在Groovy中使用Template框架,因此可以解决您的问题:
You can use the Template framework in Groovy, so doing this solves your problem:
String stringFromDatabase = 'Hello ${name}!'
String name = 'world'
def engine = new groovy.text.SimpleTemplateEngine()
assert 'Hello world!'== engine.createTemplate(stringFromDatabase).make([name:name]).toString()
您可以在此处找到文档: http://docs.groovy-lang.org/latest/html/documentation/template-engines.html#_introduction
You can find the docs here: http://docs.groovy-lang.org/latest/html/documentation/template-engines.html#_introduction
GString类是抽象的,抽象类的GStringImpl实现对字符串数组起作用,该字符串数组是从解析阶段与值一起获得的.
The GString class is abstract, and the GStringImpl implementation of the abstract class works on the arrays of strings, that it gets from the parsing phase along with values.
这篇关于如何在Groovy中将String转换为GString并替换占位符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!