5

在 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 应用程序的自定义错误页面。

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

4

6 回答 6

18

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

根据你的老师你应该。

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

虽然在您提供的示例中它没有多大意义,但在使用其他类型的消息或 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!

那么这将是有道理的。

文档中描述了 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));

fileCount 具有不同值的输出:

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

因此,也许您的老师正在让您知道您拥有的可能性。

于 2009-10-14T15:43:45.510 回答
1

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

于 2009-10-14T15:40:47.873 回答
1

但我看不出在这种情况下使用 MessageFormat 的意义

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

  • 按语言本地化消息
  • 在不修改源代码的情况下编辑外部消息
于 2009-10-14T15:43:28.587 回答
0

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

于 2009-10-14T15:41:57.433 回答
0

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

于 2009-10-14T15:45:45.273 回答
0

当然,如果您不需要国际化,那就是开销,但基本上讲授的代码希望它更“国际化”(尽管实际上并未国际化,因为字符串仍然是硬编码的)。

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

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

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.

于 2009-10-14T15:49:01.937 回答