Java属性中的动态占位符替换 [英] Dynamic Placeholder substitution in properties in java
问题描述
我想在Java应用程序的属性中动态替换占位符.像
I wanted to substitute the placeholder dynamically in properties in a java application. Like
WelcomeMessage=Welcome Mr. {firstName} {lastName} !!!
这些firstName和LastName变量需要动态替换.我们应该使用速度模板引擎吗?还是有其他相同的开源框架?
These firstName and LastName variable needs to be substituted dynamically. Should we use velocity template engine for the same? Or are there any other opensource frameworks for the same?
谢谢, 曼尼什(Manish)
Thanks, Manish
推荐答案
You can use the MessageFormat class of Java SE. It allows you to do exactly what you ask for.
在您的情况下,假设props包含从文件中加载的所有属性,则下面的代码段就可以解决问题.
In your case the below code snippet must do the trick, assuming props contains all the properties loaded from your file.
MessageFormat.format((String) props.get("WelcomeMessage"), "First", "Last");
请注意,您的属性文件应具有参数索引,而不是如下所示的命名参数.
Note that your properties files should have index of parameters instead of named parameters as below.
WelcomeMessage=Welcome Mr. {0} {1} !!!
这篇关于Java属性中的动态占位符替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!