小编Ram*_*rro的帖子

MessageFormat在Java中的优点

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

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

java string concatenation messageformat

5
推荐指数
1
解决办法
1万
查看次数

Java中this关键字的其他用法

(对于那些阅读我之前的问题的人来说,这是同一个老师和同一个项目.)

我的老师"检查了"我的代码以获取Web应用程序项目并提供了一些建议.其中一个建议是this在这种情况下使用关键字:

private String getUsername() {
    return username;
}
Run Code Online (Sandbox Code Playgroud)

因此,如果我遵循他的建议,那将成为:

private String getUsername() {
    return this.username;
}
Run Code Online (Sandbox Code Playgroud)

我问他为什么,他告诉我除了清除歧义之外,还有另一种用法.快速的Google搜索没有返回此关键字的其他用法的结果.即使是SunJava教程也没有提到适合这种情况的其他用法.

java this keyword javabeans

0
推荐指数
1
解决办法
4324
查看次数

标签 统计

java ×2

concatenation ×1

javabeans ×1

keyword ×1

messageformat ×1

string ×1

this ×1