【问题标题】:How does the constructor for the javamail Authenticator work? [duplicate]javamail Authenticator 的构造函数是如何工作的? [复制]
【发布时间】:2016-03-29 06:19:32
【问题描述】:

我正在尝试编写一个简单的 Java 程序,它只发送电子邮件并从我的收件箱中的电子邮件中检索文本,但我对 Authenticator 对象的工作方式有点困惑。为什么在构造函数之后立即有括号中的代码,它是如何工作的?我找到了这个用于创建 Session 对象的示例代码,它运行良好,但我以前从未见过这种表示法,也无法在其他地方找到它的任何其他示例。

Session session = Session.getInstance(props,
  new javax.mail.Authenticator() {
     protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
     }
  });

【问题讨论】:

    标签: java constructor jakarta-mail authenticator


    【解决方案1】:

    来自The Java™ Tutorials - Anonymous Classes:

    匿名类使您的代码更简洁。它们使您能够同时声明和实例化一个类。它们类似于本地类,只是它们没有名称。如果您只需要使用一次本地类,请使用它们。

    来自JAVAMAIL API FAQ:

    更直接的方法是在连接到 Store 时调用使用用户名和密码的 connect 方法。发送消息时,使用带有用户名和密码的静态 Transport.send 方法。

    【讨论】:

    • 啊,这很有意义。谢谢,这正是我需要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多