在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所说:
我怀疑最终用户会看到此异常,因为无论如何它只会由应用程序日志显示,并且我为Web应用程序提供了一个自定义错误页面。
我应该更改代码行还是坚持使用当前代码?
最佳答案
根据您的老师,您应该。
也许他想让您为同一件事学习不同的方法。
虽然在您提供的示例中这没有多大意义,但在使用其他类型的消息或用于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的另一种用法
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.
因此,也许您的老师正在让您知道您所拥有的可能性。
关于java - Java中MessageFormat的好处,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1567146/