无法在Java中访问父级的受保护方法

时间:2014-07-22 10:39:32

标签: java email javamail

我有这个问题:

包含内部类的java类。内部类(Authenticator)扩展了javax.mail.Authenticator(注意类和子类的相同名称)。

问题是我无法访问受保护的方法getPasswordAuthentication,除非内部类与扩展类具有相同的名称(我的意思是Authenticator extends javax.mail.Authenticator)。 如果我写private class SMTPAuthenticator extends javax.mail.Authenticator,那么我就无法再访问受保护的getPasswordAuthentication了。 请参阅以下代码:

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailWithPasswordAuthentication {
    public static void main(String[] args) throws MessagingException {
        new MailWithPasswordAuthentication().run();
    }

    private void run() throws MessagingException {
        Message message = new MimeMessage(getSession());

        message.addRecipient(RecipientType.TO, new InternetAddress("to@example.com"));
        message.addFrom(new InternetAddress[] { new InternetAddress("from@example.com") });

        message.setSubject("the subject");
        message.setContent("the body", "text/plain");

        Transport.send(message);
    }

    private Session getSession() {
        Authenticator authenticator = new Authenticator();

        Properties properties = new Properties();
        properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
        properties.setProperty("mail.smtp.auth", "true");

        properties.setProperty("mail.smtp.host", "mail.example.com");
        properties.setProperty("mail.smtp.port", "25");

        return Session.getInstance(properties, authenticator);
    }

    private class Authenticator extends javax.mail.Authenticator {
        private PasswordAuthentication authentication;

        public Authenticator() {
            String username = "auth-user";
            String password = "auth-password";
            authentication = new PasswordAuthentication(username, password);
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }
}

thankx, 甲

2 个答案:

答案 0 :(得分:2)

如果将Authenticator类重命名为SMTPAuthenticator,则还应更改该行:

Authenticator authenticator = new Authenticator();

SMTPAuthenticator authenticator = new SMTPAuthenticator();

您收到错误的原因是只有SMTPAuthenticator类包含getPasswordAuthentication()方法,而不包含基础Authenticator

答案 1 :(得分:0)

如果您可以访问Authenticator extends javax.mail.Authenticatore,那么您应该可以访问class SMTPAuthenticator extends javax.mail.Authenticator。如果没有,那么你的观察是错误的。