MimeMessage не может использовать внутренний класс - PullRequest
0 голосов
/ 31 января 2020

Мы пытаемся запустить некоторый стандартный код Java для отправки сообщения через Javamail из приложения третьей части, проблема в том, что в приложении есть ошибка, означающая, что оно не может использовать внутренние классы.

Прежде чем кто-либо спросит, пожалуйста, не просите исправить приложение, так как оно не находится под нашим контролем. Компания, владеющая приложением, предложила другим решить эту проблему, создав отдельный класс вместо использования внутреннего класса RecipientType в setRecipients.

. Мы пытались безрезультатно заставить это работать создание нового класса для RecipientType, хотя у нас возникают проблемы со ссылками на него, так как он не является методом внутри setRecipients.

Был бы признателен, если у кого-то есть идея, как обойти необходимость использования внутренний класс в MimeMessage? Есть ли способ, которым мы можем жестко закодировать это?

Дополнительная информация:

Это то, что мы называем в приложении

// new MIME message, version 1.0:

javax.mail.Message message = new javax.mail.internet.MimeMessage(session);

message.setHeader("MIME-Version" , "1.0" );

message.setFrom(new javax.mail.internet.InternetAddress(fromEmailAddress, fromEmailPersonal ));

message.setRecipients(javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress.parse(  recipientEmailAddress ));

message.setSubject( emailSubject );

message.setText(emailBody);

javax.mail.Transport.send(message);

Это раздел сообщения. java сбой

    /**
     * This inner class defines the types of recipients allowed by
     * the Message class. The currently defined types are TO,
     * CC and BCC.
     *
     * Note that this class only has a protected constructor, thereby
     * restricting new Recipient types to either this class or subclasses.
     * This effectively implements an enumeration of the allowed Recipient
     * types.
     *
     * The following code sample shows how to use this class to obtain
     * the "TO" recipients from a message.
     * 
     *
     * Message msg = folder.getMessages(1);
     * Address[] a = m.getRecipients(Message.RecipientType.TO);
     *
     * 
* * @see javax.mail.Message # getRecipients * @see javax.mail.Message # setRecipients * @see javax.mail.Message # addRecipients * / publi c stati c Класс RecipientType реализует Сериализуемые {/ ** * Получатели "To" (первичные). * / publi c stati c final RecipientType TO = новый RecipientType ("To"); / ** * Получатели "Cc" (копия). * / publi c stati c final RecipientType CC = new RecipientType ("Cc"); / ** * Получатели "B cc" (слепая копия). * / publi c stati c final RecipientType B CC = new RecipientType ("B cc"); / ** * Тип получателя, обычно имя соответствующего * Inte rnet стандартного заголовка. * * @serial * / защищенный тип String; частный статус c окончательный длинный serialVersionUID = -7479791750606340008L; / ** * Конструктор для использования подклассами. * * @param type тип получателя * / protected RecipientType (тип String) {this.type = type; } / ** * При десериализации RecipientType мы должны убедиться, что * вернули только один из известных stati c конечных экземпляров, определенных * в этом классе. Подклассы должны реализовать свой собственный метод * readResolve, который проверяет их известные * экземпляры перед вызовом этого супер-метода. * * @return экземпляр объекта RecipientType * @exception ObjectStreamException для ошибок потока объекта * / protected Object readResolve () throws ObjectStreamException {if (type.equals ("To")) return TO; иначе if (type.equals ("Cc")) возвращает CC; иначе if (type.equals ("B cc")) возвращает BCC; иначе бросить новое InvalidObjectException («Попытаться разрешить неизвестный RecipientType:» + type); } @Override publi c String toString () {возвращаемый тип; }}

Это пользовательский класс, который мы пытались реализовать вместо внутреннего класса, помеченный RecipientType

import javax.mail.*;
import javax.activation.*;
import java.lang.*;
import java.io.*;
import java.util.*;
import java.text.ParseException;

 public class RecipientType implements Serializable {
    /**
     * The "To" (primary) recipients.
     */
    public static final RecipientType TO = new RecipientType("To");
    /**
     * The "Cc" (carbon copy) recipients.
     */
    public static final RecipientType CC = new RecipientType("Cc");
    /**
     * The "Bcc" (blind carbon copy) recipients.
     */
    public static final RecipientType BCC = new RecipientType("Bcc");

    /**
     * The type of recipient, usually the name of a corresponding
     * Internet standard header.
     *
     * @serial
     */
    protected String type;

    private static final long serialVersionUID = -7479791750606340008L;

    /**
     * Constructor for use by subclasses.
     *
     * @param   type    the recipient type
     */
    protected RecipientType(String type) {
        this.type = type;
    }

    /**
     * When deserializing a RecipientType, we need to make sure to
     * return only one of the known static final instances defined
     * in this class.  Subclasses must implement their own
     * <code>readResolve</code> method that checks for their known
     * instances before calling this super method.
     *
     * @return  the RecipientType object instance
     * @exception   ObjectStreamException for object stream errors
     */
    protected Object readResolve() throws ObjectStreamException {
        if (type.equals("To"))
        return TO;
        else if (type.equals("Cc"))
        return CC;
        else if (type.equals("Bcc"))
        return BCC;
        else
        throw new InvalidObjectException(
            "Attempt to resolve unknown RecipientType: " + type);
    }

    @Override
    public String toString() {
        return type;
    }
}

Вот как мы пытались реализовать пользовательский класс

message.setRecipients(RecipientType.TO, 
javax.mail.internet.InternetAddress.parse(  recipientEmailAddress ));

Мы получаем следующую ошибку: Невозможно разобрать выражение; неопределенный метод: addRecipient для класса: javax.mal.Message (строка: 29, столбец: 2)

...