[Java方法链接(可选地,基于参数)

问题描述 投票:1回答:2

[如果第三方在方法中请求参数attachments,我知道我的参数可能为空,如何避免使用if和中断方法链接?该方法具有以下定义。

// import org.jetbrains.annotations.NotNull;
EmailBuilder withAttachments(@NotNull List<Attachment> attachments);

我希望NOT使用.withAttachments的if条件,当附件== null时。我知道javascript具有method?(),但是什么适用于java8或更高版本?在(附件== null)的情况下,我根本不想调用.withAttachments()。但是,在JavaScript或打字稿中,我看不到语法可与methodA?()相提并论。

return emailBuilder()
  .withSubject(email.getSubject())
  .withReplyTo(replyAddresses)
  .withAttachments(attachments) // This is conditional...based on attachments
  .withHeader("X-showheader", email.getShowHeader());
  .build();

我需要这样做吗?

EmailBuilder eb = emailBuilder()
  .withSubject(email.getSubject())
  .withReplyTo(replyAddresses);
  if(attachments)
    eb = eb.withAttachments(attachments); // This is conditional...based on attachments
  eb = eb.withHeader("X-showheader", email.getHeader())
  .build;
return eb;
java optional method-chaining notnull
2个回答
3
投票

如果withAttachments()不允许使用null值,那么是的,您需要if (attachments != null)

但是,由于构建器通常不需要特定的方法调用顺序,因此您可以稍微清理一下代码。

EmailBuilder eb = emailBuilder()
        .withSubject(email.getSubject())
        .withReplyTo(replyAddresses)
        .withHeader("X-showheader", email.getHeader());
if (attachments != null)
    eb.withAttachments(attachments);
return eb.build();

1
投票

我假设您无法更改withAttachments的合同以忽略具有null的呼叫?您可以在Optional中上游包装附件,然后为orElse提供一个空的但不为null的attachments类型的隐含内容,例如(假设attachmentsList):

Optional<...> optionalAttachments = Optional.ofNullable(attachments);

...

.withAttachments(optionalAttachments.orElse(Collections.emptyList())

UPDATE(基于来自评论的提示,给安德里亚斯的建议)

您也可以通过三元来实现,例如:

.withAttachments(attachments != null ? attachments : Collections.emptyList())
© www.soinside.com 2019 - 2024. All rights reserved.