以下Java方法创建具有固定用户名和密码的JavaMail密码 validator :
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;
}
...但这没有用。
有人知道这个问题的解决办法吗?
最佳答案
这里:
return new Authenticator() {
创建一个匿名内部类!换句话说:您正在隐式创建一个新类,并实例化该类的对象。您的新类正在扩展它派生的类,因此您可以重写 { block } 中的方法。
简单的解决方案是明确地实现这一点:创建一个“真正的”java 类,该类将用户名、密码作为构造函数参数,并像在第一个示例中那样使用它们。然后只需让 Java 脚本代码实例化该类并传递所需的参数即可。
不要模仿实现细节,而是关注需要完成的事情(创建具有特定行为的类的对象)!
关于java - 在 Nashorn JavaScript 中重写 Java 类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54691437/