以下 Java方法创建具有固定用户名和密码的JavaMail密码验证器:
public static Authenticator createJavamailPasswordAuthenticator(String username,String password) {
final String usernameTmp = username;
final String passwordTmp = password;
return new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(usernameTmp,passwordTmp);
}
};
}
我需要编写一个完全相同的 Nashorn JavaScript函数,但是我不知道如何重写Authenticator的getPasswordAuthentication Java方法。作为Nashorn绿角,我尝试了以下
function createJavamailPasswordAuthenticator(username,password){
var authenticator=new javax.mail.Authenticator();
authenticator.getPasswordAuthentication=function(){
return new javax.mail.PasswordAuthentication(username,password);
}
return authenticator;
}
...但是那没用。
有人知道解决方案吗?
答案 0 :(得分:1)
这里:
return new Authenticator() {
创建一个匿名内部类!换句话说:您正在隐式创建一个新类,并实例化该类的对象。您的新类扩展了它的派生类,因此您可以覆盖{block}中的方法。
简单的解决方案是使该 explicit :创建一个“真实的” java类,该类使用用户名,密码作为构造函数参数,并像在第一个示例中一样使用它们。然后,只需让Java脚本代码实例化 that 类并传递所需的参数即可。
不要模仿实现细节,而要专注于需要做的事情(创建具有特定行为的类的对象)!