示例
我见过 .properties 文件的约定类似于以下内容:
示例 1:
error.connection="Could not connect to host {0}, with IP address: {1}"
示例 2:
error.connection="Could not connect to host %s, with IP address: %s."
(和如下所示的 XML 文件)示例 3:
<Error id="connection">Could not connect to host {0}, with IP address {1}</Error>
示例 2 中定义的错误消息可以这样处理:
// Get error.connection value from .properties file and store it in a variable named ERROR_MESSAGE.
String errorMessage = String.format(ERROR_MESSAGE, hostname, ipAddress);
这种方法看起来笨拙且危险,因为它要求错误消息的用户在调用 String.format
时知道消息字符串需要多少个变量
问题
定义和处理变量错误消息的最佳实践(包括可用工具)是什么? 这种做法叫什么?
最佳答案
Java 教程建议使用 MessageFormat: http://docs.oracle.com/javase/tutorial/i18n/format/messageFormat.html
您仍然需要知道参数的顺序,但通常一条消息只在一个地方使用。如果您在多个地方需要相同的消息,您可以使用方法和强类型参数包装调用。
关于java - 如何在 Java 中正确定义和处理参数化错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9420933/