我有一种方法来验证电子邮件的收件人。
在我的代码中 .map(Recipient::getId)
产生错误:
Non static method cannot be reference from a static context.
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"));
}
收件人
类:
@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
接口(interface):
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"));
}
关于Java 8Optional.ofNullable.map产生非静态方法引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50813290/