Java 中 MessageFormat 的优点

发布于 2024-08-07 13:28:48 字数 723 浏览 2 评论 0原文

在 Struts2 Web 应用程序的某个 Java 类中,我有这样一行代码:

try {
    user = findByUsername(username);
} catch (NoResultException e) {
    throw new UsernameNotFoundException("Username '" + username + "' not found!");
}

我的老师希望我将 throw 语句更改为如下所示:

static final String ex = "Username '{0}' not found!" ;
// ...
throw new UsernameNotFoundException(MessageFormat.format(ex, new Object[] {username}));

但我不认为在这种情况下使用 MessageFormat 有何意义。是什么让它比简单的字符串连接更好?正如 MessageFormat 的 JDK API 所说:

MessageFormat 提供了一种以与语言无关的方式生成串联消息的方法。使用它来构建向最终用户显示的消息。

我怀疑最终用户是否会看到此异常,因为无论如何它只会由应用程序日志显示,而且我有一个针对 Web 应用程序的自定义错误页面。

我应该更改代码行还是坚持使用当前代码行?

In a certain Java class for a Struts2 web application, I have this line of code:

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:

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 provides a means to produce concatenated messages in language-neutral way. Use this to construct messages displayed for end users.

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.

Should I change the line of code or stick with the current?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

Spring初心 2024-08-14 13:28:48

我应该更改代码行还是坚持使用当前代码行?

根据您的老师的说法,您应该这样做。

也许他希望你学习同一件事的不同方法。

虽然在您提供的示例中它没有多大意义,但在使用其他类型的消息或 i18n 时它会很有用,

请考虑一下:

String message = ResourceBundle.getBundle("messages").getString("user.notfound");

throw new UsernameNotFoundException(MessageFormat.format( message , new Object[] {username}));

您可以有一个 messages_en.properties 文件和一个 messages_es.properties

第一个带有字符串:

user.notfound=Username '{0}' not found!

第二个带有:

user.notfound=¡Usuario '{0}' no encontrado!

那么这就有意义了。

doc

 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));

fileCount 具有不同值的输出:

 The disk "MyDisk" contains no files.
 The disk "MyDisk" contains one file.
 The disk "MyDisk" contains 1,273 files.

所以也许您的老师正在让您知道您拥有的可能性。

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

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.properties file and a 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 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.

葬心 2024-08-14 13:28:48

教师方式可以更轻松地进行本地化,因为您可以提取单个字符串而不是几个小位。

Teachers way allows for easier localisation as you can extract a single string rather than several little bits.

泪之魂 2024-08-14 13:28:48

但我不明白使用的意义
这种情况下的 MessageFormat

在这种特定情况下,它不会给您带来太多好处。一般来说,使用 MessageFormat 允许您将这些消息外部化到文件中。这允许您:

  • 按语言本地化消息
  • 在外部编辑消息,而无需
    修改源代码

But I don't see the point of using
MessageFormat in this situation

In that specific situation it doesn't buy you much. In general, using MessageFormat allows you to externalize those messages in a file. This allows you to:

  • localize the messages by language
  • edit the messages outside without
    modifying source code
执笔绘流年 2024-08-14 13:28:48

就我个人而言,我会坚持使用串联方式,但这只是一个偏好问题。有些人认为将带有变量的字符串作为一个字符串编写,然后在字符串后面将参数作为列表传递,这样会更干净。字符串中的变量越多,使用 MessageFormat 就越有意义,但你只有一个,所以区别不大。

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.

残龙傲雪 2024-08-14 13:28:48

当然,如果您不需要国际化,那么这是开销,但基本上,老师希望的代码更加“国际化”(尽管实际上并没有国际化,因为字符串仍然是硬编码的)。

由于这是一个教学情况,尽管他这样做可能只是为了向您展示如何使用这些课程,而不是作为针对该特定示例进行编程的最佳方式。

就最佳编程方式而言,如果需要国际化,那么您需要为其编写代码,如果不需要,则不需要。我只是无缘无故地增加了开销和时间(编写代码)。

与其他答案同步,MessageFormat 对于国际化的重要性不仅仅是它使创建外部文件变得更容易。在其他语言中,参数的位置在消息的句子结构中可能有所不同,因此使用 MessageFormat 允许您根据语言更改该位置,而字符串连接则不会。

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.

痴情换悲伤 2024-08-14 13:28:48

我发现使用 MessageFormat 的一个优点是,当您决定外部化字符串时,构建消息会更容易,而且查看更有意义“未找到用户名‘{0}’!”在您的资源文件中作为一个字符串仅由一个 ID 访问。

One advantage that I see in using MessageFormat is that when you decide to externalize your 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文