Java 中 MessageFormat 的好处
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1567146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Benefits of MessageFormat in Java
提问by Ramon Marco L. Navarro
In a certain Java class for a Struts2 web application, I have this line of code:
在 Struts2 Web 应用程序的某个 Java 类中,我有这行代码:
try {
user = findByUsername(username);
} catch (NoResultException e) {
throw new UsernameNotFoundException("Username '" + username + "' not found!");
}
My teacher wants me to change the throw statement into something like this:
我的老师要我把 throw 语句改成这样:
static final String ex = "Username '{0}' not found!" ;
// ...
throw new UsernameNotFoundException(MessageFormat.format(ex, new Object[] {username}));
But I don't see the point of using MessageFormat in this situation. What makes this better than simple string concatenation? As the JDK API for MessageFormat says:
但我不认为在这种情况下使用 MessageFormat 有什么意义。是什么让这比简单的字符串连接更好?正如 MessageFormat 的 JDK API 所说:
MessageFormat provides a means to produce concatenated messages in language-neutral way. Use this to construct messages displayed for end users.
MessageFormat 提供了一种以与语言无关的方式生成连接消息的方法。使用它来构建为最终用户显示的消息。
I doubt that the end users would see this exception since it would only be displayed by the application logs anyway and I have a custom error page for the web application.
我怀疑最终用户是否会看到此异常,因为无论如何它只会由应用程序日志显示,而且我有一个用于 Web 应用程序的自定义错误页面。
Should I change the line of code or stick with the current?
我应该更改代码行还是坚持当前的代码行?
回答by OscarRyz
Should I change the line of code or stick with the current?
我应该更改代码行还是坚持当前的代码行?
According to your teacher your should.
根据你的老师你应该。
Perhaps he wants you to learn different approaches for the same thing.
也许他想让你为同一件事学习不同的方法。
While in the sample you provided it doesn't make much sense, it would be useful when using other types of messages or for i18n
虽然在您提供的示例中它没有多大意义,但在使用其他类型的消息或 i18n 时会很有用
Think about this:
想一想:
String message = ResourceBundle.getBundle("messages").getString("user.notfound");
throw new UsernameNotFoundException(MessageFormat.format( message , new Object[] {username}));
You could have a messages_en.propertiesfile and a messages_es.properties
你可以有一个messages_en.properties文件和一个messages_es.properties
The first with the string:
第一个字符串:
user.notfound=Username '{0}' not found!
And the second with:
第二个是:
user.notfound=?Usuario '{0}' no encontrado!
Then it would make sense.
那么就说得通了。
Another use of the MessageFormat is described in the doc
文档中描述了 MessageFormat 的另一种用法
MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
double[] filelimits = {0,1,2};
String[] filepart = {"no files","one file","{0,number} files"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
form.setFormatByArgumentIndex(0, fileform);
int fileCount = 1273;
String diskName = "MyDisk";
Object[] testArgs = {new Long(fileCount), diskName};
System.out.println(form.format(testArgs));
The output with different values for fileCount:
具有不同文件计数值的输出:
The disk "MyDisk" contains no files.
The disk "MyDisk" contains one file.
The disk "MyDisk" contains 1,273 files.
So perhaps your teacher is letting you know the possibilities you have.
所以也许你的老师让你知道你拥有的可能性。
回答by Steve
Teachers way allows for easier localisation as you can extract a single string rather than several little bits.
教师方式允许更轻松的本地化,因为您可以提取单个字符串而不是几个小位。
回答by Kevin
But I don't see the point of using MessageFormat in this situation
但我看不出在这种情况下使用 MessageFormat 的意义
In that specificsituation it doesn't buy you much. In general, using MessageFormat allows you to externalize those messages in a file. This allows you to:
在那种特定情况下,它不会给你带来太多好处。通常,使用 MessageFormat 允许您在文件中外部化这些消息。这允许您:
- localize the messages by language
- edit the messages outside without modifying source code
- 按语言本地化消息
- 在不修改源代码的情况下编辑外部消息
回答by Jez
Personally, I would stick with the concatenation way, but it's just a matter of preference. Some people think it's cleaner to write a string with variables as one string, and then pass the params as a list after the string. The more variables you have in the string, the more sense using MessageFormat makes, but you only have one, so it's not a big difference.
就个人而言,我会坚持使用串联方式,但这只是一个偏好问题。有些人认为将一个带有变量的字符串写成一个字符串,然后将参数作为列表传递到字符串之后会更干净。字符串中的变量越多,使用 MessageFormat 的意义就越大,但您只有一个,所以差别不大。
回答by bruno conde
One advantage that I see in using MessageFormatis that when you decide to externalizeyour strings, it would be much easier to build the message and also, it makes more sense to see "Username '{0}' not found!" in your resource file as one string accessed by only one ID.
我在使用中看到的一个优点MessageFormat是,当您决定将字符串外部化时,构建消息会容易得多,而且看到“未找到用户名 '{0}'!”也更有意义。在您的资源文件中作为一个字符串,仅由一个 ID 访问。
回答by Yishai
Of course if you don't need internationalization, it is overhead, but basically the code as the teach wants it is more "internationalizable" (although not actually internationalized as the string is still hard coded).
当然,如果你不需要国际化,这是开销,但基本上教学想要的代码更“国际化”(尽管实际上没有国际化,因为字符串仍然是硬编码的)。
Since this is a teaching situation, though he may be doing it just to show you how to use those classes rather than as the best way to program for this specific example.
由于这是一种教学情况,尽管他这样做可能只是为了向您展示如何使用这些类,而不是作为针对此特定示例进行编程的最佳方式。
In terms of the best way to program, if internationalization is a requirement, then you need to code for it, if not then don't. I just adds overhead and time (to write the code) for no reason.
就编程的最佳方式而言,如果需要国际化,那么您需要为其编写代码,否则就不要。我只是无缘无故地增加了开销和时间(编写代码)。
Pace the other answers, the importance of MessageFormat for internationalizion is not just that it makes it easier to make an external file. In other languages the location of the parameter may be different in the sentence structure of the messages, so using MessageFormat allows you to change that per language, something that string concatenation would not.
跟其他答案一样,MessageFormat 对国际化的重要性不仅在于它使制作外部文件变得更容易。在其他语言中,参数的位置在消息的句子结构中可能不同,因此使用 MessageFormat 允许您更改每种语言的位置,而字符串连接则不会。

