Do resource bundles in Java support runtime string substitution?

2022-09-01 01:52:45

Can you do the following with a Java ResourceBundle?

In the properties file...

example.dynamicresource=You currently have {0} accounts.

At runtime...

int accountAcount = 3;
bundle.get("example.dynamicresource",accountCount,param2,...);

To give a result of

"You currently have 3 accounts."


答案 1

Not without using the MessageFormat class, such as:

String pattern = bundle.getString("example.dynamicresource");
String message = MessageFormat.format(pattern, accountCount);

答案 2

On their own, does not support property placeholders. The usual idea is to take the String you get from the bundle, and stick it into a , and then use that to get your parameterized message.ResourceBundleMessageFormat

If you're using JSP/JSTL, then you can combine and to do this, which uses and under the covers.<fmt:message><fmt:param>ResourceBundleMessageFormat

If you happen to be using Spring, then it has the which does something similar, and can be used anywhere in your program. This abstraction (combined with ) is much nicer to use than .ResourceBundleMessageSourceMessageSourceMessageSourceAccessorResourceBundle


推荐