Ram*_*rro 5 java string concatenation messageformat
在Struts2 Web应用程序的某个Java类中,我有这行代码:
try {
user = findByUsername(username);
} catch (NoResultException e) {
throw new UsernameNotFoundException("Username '" + username + "' not found!");
}
Run Code Online (Sandbox Code Playgroud)
我的老师要我将throw语句更改为:
static final String ex = "Username '{0}' not found!" ;
// ...
throw new UsernameNotFoundException(MessageFormat.format(ex, new Object[] {username}));
Run Code Online (Sandbox Code Playgroud)
但是我没有看到在这种情况下使用MessageFormat的意义.是什么让这比简单的字符串连接更好?正如MessageFormat的JDK API所说:
MessageFormat提供了一种以与语言无关的方式生成连接消息的方法.使用此选项可构建为最终用户显示的消息.
我怀疑最终用户会看到这个异常,因为它只会由应用程序日志显示,我有一个Web应用程序的自定义错误页面.
我应该更改代码行还是坚持使用当前代码?
Osc*_*Ryz 18
我应该更改代码行还是坚持使用当前代码?
根据你的老师,你应该.
也许他希望你为同一件事学习不同的方法.
虽然在您提供的示例中没有太大意义,但在使用其他类型的消息或i18n时它会很有用
想一想:
String message = ResourceBundle.getBundle("messages").getString("user.notfound");
throw new UsernameNotFoundException(MessageFormat.format( message , new Object[] {username}));
Run Code Online (Sandbox Code Playgroud)
你可以有一个messages_en.properties文件和一个messages_es.properties
第一个带字符串:
user.notfound=Username '{0}' not found!
Run Code Online (Sandbox Code Playgroud)
第二个:
user.notfound=¡Usuario '{0}' no encontrado!
Run Code Online (Sandbox Code Playgroud)
那会有意义.
文档中描述了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));
Run Code Online (Sandbox Code Playgroud)
fileCount的输出值不同:
The disk "MyDisk" contains no files.
The disk "MyDisk" contains one file.
The disk "MyDisk" contains 1,273 files.
Run Code Online (Sandbox Code Playgroud)
所以也许你的老师会让你知道你的可能性.