本文介绍了是否应将java.text.MessageFormat用于没有占位符的本地化消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在为运行在Java 5上的Web应用程序本地化用户界面文本,并且在如何输出属性文件中定义的消息方面存在两难选择- java.util.Properties .

We are localising the user-interface text for a web application that runs on Java 5, and have a dilemma about how we output messages that are defined in properties files - the kind used by java.util.Properties.

某些消息包含占位符,将使用 java.text.MessageFormat .例如:

Some messages include a placeholder that will be filled using java.text.MessageFormat. For example:

search.summary = Your search for {0} found {1} items.

MessageFormat很烦人,因为单引号是特殊字符,尽管在英语文本中很常见.您必须输入两个单引号:

MessageFormat is annoying, because a single quote is a special character, despite being common in English text. You have to type two for a literal single quote:

warning.item = This item''s {0} is not valid.

但是,在应用程序的1000条左右的消息中,有四分之三不包含占位符.这意味着我们可以直接输出它们,而不必使用MessageFormat,而将单引号留空:

However, three-quarters of the application's 1000 or so messages do not include a placeholder. This means that we can output them directly, avoiding MessageFormat, and leave the single quotes alone:

help.url = The web page's URL

问题:我们应该为所有消息使用MessageFormat还是采用一致的语法,还是应尽量避免使用MessageFormat,这样大多数消息都不需要转义?

Question: should we use MessageFormat for all messages, for consistent syntax, or avoid MessageFormat where we can, so most messages do not need escaping?

这两种方式都有明显的优缺点.

There are clearly pros and cons either way.

请注意,MessageFormat的API文档已确认该问题并提出了非解决方案:

Note that the API documentation for MessageFormat acknowledges the problem and suggests a non-solution:

推荐答案

只需编写您自己的MessageFormat实现即可,而无需使用此烦人的功能.您可以查看 SLF4J Logger 的代码.

Just write your own implementation of MessageFormat without this annoying feature. You may look at the code of SLF4J Logger.

它们具有自己的消息格式化程序版本,可以按以下方式使用:

They have their own version of message formatter which can be used as followed:

logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);

空占位符可以按默认顺序使用,并在某些本地化情况下进行编号,其中不同的语言会对单词或句子的一部分进行置换.

Empty placeholders could be used with default ordering and numbered for some localization cases where different languages do permutations of words or parts of sentences.

这篇关于是否应将java.text.MessageFormat用于没有占位符的本地化消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 15:44