我有一种方法可以验证电子邮件的收件人。
在我的代码中.map(Recipient::getId)
产生错误:
不能从静态上下文引用非静态方法。
private Long verifyRecipient(Long recipientId) throws NotFoundException {
return Optional.ofNullable(recipientRepository.findById(recipientId))
.map(Recipient::getId)
.orElseThrow(()-> new NotFoundException("recipient with ID" + recipientId +
" was not found"));
}
Recipient
类:
@Entity
public class Recipient {
@Id
@GeneratedValue
private Long id;
@NotBlank
private String name;
@NotBlank
@Email
@Column(unique = true)
private String emailAddress;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
我在内存数据库中使用 SpringBoot 和 H2。
所以我还有一个RecipientRepository
接口:
public interface RecipientRepository extends JpaRepository<Recipient, Long> {}
findById()
方法的定义:
Optional<T> findById(ID var1);
该方法findById()
已经返回一个Optional<T>
,因此在这种情况下,您不需要用额外的Optional.ofNullable()
包装结果。
实际上,这行:
Optional.ofNullable(recipientRepository.findById(recipientId));
返回Optional<Optional<Recipient>>
,这是多余的。
相反,你可以只写:
private Long verifyRecipient(Long recipientId) throws NotFoundException {
return recipientRepository.findById(recipientId)
.map(Recipient::getId)
.orElseThrow(() ->
new NotFoundException("Recipient with ID " + recipientId + " was not found"));
}