有没有一种方法可以推断Java中的泛型类型?

时间:2018-07-11 22:20:09

标签: java spring spring-boot generics javamail

我想创建一种用于发送带有附件的电子邮件的通用方法,我当时正在考虑使用以下方法:

public class MailAttachment<T> {

    private String attachmentName;
    private T attachment;

    public MailAttachment(String attachmentName, T attachment) {
        super();
        this.attachmentName = attachmentName;
        this.attachment = attachment;
    }
    //Getters and setters

}

稍后,发送通用类型,并让Java在编译时确定所发送的实例类型。但是编译器添加了一个错误,指出需要将其强制转换为正确的类型(文件,数据源,输入流源)。

   @Autowired
    private JavaMailSender mailSender;

 public void sendHtmlMail(Mail mail, MailAttachment<?> attachment) {
            new Thread(() -> {
                try {
                    MimeMessage message = mailSender.createMimeMessage();
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);

                    helper.setTo(mail.getTo());
                    helper.setSubject(mail.getSubject());
                    helper.setFrom(host);
                    message.setContent(mail.getContent(), "text/html");
                    if (attachment != null) {    
                        //Casting error 
                   helper.addAttachment(attachment.getAttachmentName(), attachment.getAttachment());
                    }
                    mailSender.send(message);
                } catch (MessagingException | MailException e) {
                    logger.error("Error sending email: ", e);
                }
            }).start();
        }

所以我不得不使用一种变通方法来验证并转换为正确的类型,如下所示:

if (attachment.getAttachment() instanceof DataSource) {
    helper.addAttachment(attachment.getAttachmentName(),
                        (DataSource) attachment.getAttachment());
} else if (attachment.getAttachment() instanceof File) {
    helper.addAttachment(attachment.getAttachmentName(),
                        (File) attachment.getAttachment());
} else if (attachment.getAttachment() instanceof InputStreamSource) {
    helper.addAttachment(attachment.getAttachmentName(),
                        (InputStreamSource) attachment.getAttachment());
}

所以,我想知道是否有更好的方法仅将这种类型的东西保留在参数中,而仅使用这种方法来检查这种东西?

1 个答案:

答案 0 :(得分:4)

创建一个可附加的接口

interface Attachable {
  void attach(Helper helper);
}

,然后针对各种类型实施此操作:

class DataSourceAttachable implements Attachable {
  String name;
  DataSource dataSource;  // Initialize in ctor.

  void attach(Helper helper) {
    helper.addAttachment(name, dataSource);
  }
}

// etc, for other types

那么就不需要泛型了

public void sendHtmlMail(Mail mail, Attachable attachable) {
  // ...
  attachable.attach(helper);
  // ...
}