javamail Authenticator 的构造函数如何工作?
How does the constructor for the javamail Authenticator work?
我正在尝试编写一个简单的 Java 程序,它只发送电子邮件并从收件箱中的电子邮件中检索文本,但我对 Authenticator 对象的工作原理有点困惑。为什么在构造函数之后紧接着有括号代码,它是如何工作的?我找到了这个用于创建 Session 对象的示例代码,它工作正常,但我以前从未见过这种表示法,也无法在其他地方找到任何其他示例。
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
来自The Java™ Tutorials - Anonymous Classes:
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
A more straightforward approach is to call the connect method that takes a username and password when connecting to a Store. When sending a message, use the static Transport.send method that takes a username and password.
我正在尝试编写一个简单的 Java 程序,它只发送电子邮件并从收件箱中的电子邮件中检索文本,但我对 Authenticator 对象的工作原理有点困惑。为什么在构造函数之后紧接着有括号代码,它是如何工作的?我找到了这个用于创建 Session 对象的示例代码,它工作正常,但我以前从未见过这种表示法,也无法在其他地方找到任何其他示例。
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
来自The Java™ Tutorials - Anonymous Classes:
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
A more straightforward approach is to call the connect method that takes a username and password when connecting to a Store. When sending a message, use the static Transport.send method that takes a username and password.